@vkontakte/videoplayer-core 2.0.48 → 2.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/build/polyfills/runtime/abortableFetch.d.ts +4 -0
  2. package/es2015.cjs.js +4 -4
  3. package/es2015.esm.js +4 -4
  4. package/es2018.cjs.js +4 -4
  5. package/es2018.esm.js +4 -4
  6. package/esnext.cjs.js +4 -4
  7. package/esnext.esm.js +4 -4
  8. package/package.json +1 -1
  9. package/{providers → packages/sdk/src/providers}/ChromecastProvider/ChromecastInitializer/types.d.ts +0 -0
  10. package/{providers → packages/sdk/src/providers}/DashIFProvider/dashjsTypes.d.ts +0 -0
  11. package/{providers → packages/sdk/src/providers}/DashLiveProvider/types.d.ts +0 -0
  12. package/{providers → packages/sdk/src/providers}/DashLiveProvider/utils/FilesFetcher.d.ts +0 -0
  13. package/{providers → packages/sdk/src/providers}/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -0
  14. package/{providers → packages/sdk/src/providers}/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -0
  15. package/{providers → packages/sdk/src/providers}/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +0 -0
  16. package/{providers → packages/sdk/src/providers}/DashProvider/types.d.ts +0 -0
  17. package/{providers → packages/sdk/src/providers}/DashProvider/utils/DashLite.d.ts +2 -2
  18. package/{providers → packages/sdk/src/providers}/DashProvider/utils/stream.d.ts +0 -0
  19. package/{providers → packages/sdk/src/providers}/DashProvider/utils/xhr2.d.ts +0 -0
  20. package/{providers → packages/sdk/src/providers}/DashVKProvider/lib/buffer.d.ts +4 -4
  21. package/{providers → packages/sdk/src/providers}/DashVKProvider/lib/ebml.d.ts +0 -0
  22. package/{providers → packages/sdk/src/providers}/DashVKProvider/lib/fetcher.d.ts +0 -0
  23. package/{providers → packages/sdk/src/providers}/DashVKProvider/lib/isobmff.d.ts +0 -0
  24. package/{providers → packages/sdk/src/providers}/DashVKProvider/lib/mpd.d.ts +0 -0
  25. package/packages/sdk/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +16 -0
  26. package/{providers → packages/sdk/src/providers}/DashVKProvider/lib/webm.d.ts +0 -0
  27. package/{providers → packages/sdk/src/providers}/ProviderContainer/types.d.ts +0 -0
  28. package/{providers → packages/sdk/src/providers}/types.d.ts +2 -2
  29. package/{providers → packages/sdk/src/providers}/utils/LiveOffset/types.d.ts +0 -0
  30. package/{utils → packages/sdk/src/utils}/StateMachine/types.d.ts +0 -0
  31. package/{utils → packages/sdk/src/utils}/StatefulIterator/StatefulIterator.spec.d.ts +0 -0
  32. package/{utils → packages/sdk/src/utils}/buffer/getTotalBufferDuration.d.ts +0 -0
  33. package/{utils → packages/sdk/src/utils}/buffer/types.d.ts +0 -0
  34. package/{utils → packages/sdk/src/utils}/link.d.ts +0 -0
  35. package/{utils → packages/sdk/src/utils}/quality/quality.spec.d.ts +0 -0
  36. package/{utils → packages/sdk/src/utils}/range.d.ts +0 -0
  37. package/{utils → packages/sdk/src/utils}/rectangle.d.ts +0 -0
  38. package/player/Player.d.ts +5 -5
  39. package/player/types.d.ts +19 -1
  40. package/player/utils/optimisticPosition.d.ts +12 -0
  41. package/player/utils/watchCoverage.d.ts +4 -4
  42. package/providers/DashIFProvider/index.d.ts +1 -1
  43. package/providers/DashLiveProvider/DashLiveProvider.d.ts +2 -2
  44. package/providers/DashVKProvider/lib/player.d.ts +1 -1
  45. package/providers/DashVKProvider/lib/types.d.ts +1 -0
  46. package/providers/HlsLiveProvider/index.d.ts +2 -2
  47. package/providers/ProviderContainer/index.d.ts +3 -3
  48. package/utils/tuningConfig.d.ts +1 -0
  49. package/player/utils/position.d.ts +0 -11
package/es2018.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.48
3
- * Thu, 16 Jun 2022 10:49:20 GMT
4
- * https://st.mycdn.me/static/playersdk/2-0-48/doc/
2
+ * @vkontakte/videoplayer-core v2.0.50
3
+ * Mon, 27 Jun 2022 09:53:35 GMT
4
+ * https://st.mycdn.me/static/playersdk/2-0-50/doc/
5
5
  */
6
- 'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2018.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce'));var a,r,o,n,u,l;exports.PlaybackState=void 0,(a=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',a.PLAYING='playing',a.PAUSED='paused',exports.VideoFormat=void 0,(r=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',r.DASH='DASH',r.DASH_SEP='DASH_SEP',r.DASH_SEP_VK='DASH_SEP_VK',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM_VK',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS_JS',r.HLS_LIVE='HLS_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(o||(o={})),exports.ChromecastState=void 0,(n=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',n.AVAILABLE='AVAILABLE',n.CONNECTING='CONNECTING',n.CONNECTED='CONNECTED',exports.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(l=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',l.HTTP2='http2',l.QUIC='quic';const d={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,enableSubSegmentBufferFeeding:!1},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1};class h{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;var a;t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(a='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',a),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,a;null===(a=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===a||a.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,a;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(a=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===a?void 0:a.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(c),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var r;const o=a===exports.ChromecastState.CONNECTED,n=t.isNonNullable(this.connection$.getValue());if(o&&!n){const a=s.getCurrentSession();t.assertNonNullable(a);const o=a.getCastDevice(),n=null===(r=a.getMediaSession())||void 0===r?void 0:r.media.contentId;(t.isNullable(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:a,castDevice:o}))}else!o&&n&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.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 c=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var p='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},m=function(t){return t&&t.Math==Math&&t},f=m('object'==typeof globalThis&&globalThis)||m('object'==typeof window&&window)||m('object'==typeof self&&self)||m('object'==typeof p&&p)||function(){return this}()||Function('return this')(),b=function(t){try{return!!t()}catch(t){return!0}},S=!b((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),v=S,g=Function.prototype,y=g.apply,T=g.call,E='object'==typeof Reflect&&Reflect.apply||(v?T.bind(y):function(){return T.apply(y,arguments)}),P=S,k=Function.prototype,w=k.bind,$=k.call,A=P&&w.bind($,$),x=P?function(t){return t&&A(t)}:function(t){return t&&function(){return $.apply(t,arguments)}},N=function(t){return'function'==typeof t},_={},D=!b((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),R=S,I=Function.prototype.call,L=R?I.bind(I):function(){return I.apply(I,arguments)},C={},O={}.propertyIsEnumerable,B=Object.getOwnPropertyDescriptor,V=B&&!O.call({1:2},1);C.f=V?function(t){var e=B(this,t);return!!e&&e.enumerable}:O;var M,F,U=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},j=x,q=j({}.toString),H=j(''.slice),G=function(t){return H(q(t),8,-1)},Y=x,Q=b,z=G,W=f.Object,J=Y(''.split),K=Q((function(){return!W('z').propertyIsEnumerable(0)}))?function(t){return'String'==z(t)?J(t,''):W(t)}:W,X=f.TypeError,Z=function(t){if(null==t)throw X('Can\'t call method on '+t);return t},tt=K,et=Z,it=function(t){return tt(et(t))},st=N,at=function(t){return'object'==typeof t?null!==t:st(t)},rt={},ot=rt,nt=f,ut=N,lt=function(t){return ut(t)?t:void 0},dt=function(t,e){return arguments.length<2?lt(ot[t])||lt(nt[t]):ot[t]&&ot[t][e]||nt[t]&&nt[t][e]},ht=x({}.isPrototypeOf),ct=f,pt=dt('navigator','userAgent')||'',mt=ct.process,ft=ct.Deno,bt=mt&&mt.versions||ft&&ft.version,St=bt&&bt.v8;St&&(F=(M=St.split('.'))[0]>0&&M[0]<4?1:+(M[0]+M[1])),!F&&pt&&(!(M=pt.match(/Edge\/(\d+)/))||M[1]>=74)&&(M=pt.match(/Chrome\/(\d+)/))&&(F=+M[1]);var vt=F,gt=b,yt=!!Object.getOwnPropertySymbols&&!gt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&vt&&vt<41})),Tt=yt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,Et=dt,Pt=N,kt=ht,wt=Tt,$t=f.Object,At=wt?function(t){return'symbol'==typeof t}:function(t){var e=Et('Symbol');return Pt(e)&&kt(e.prototype,$t(t))},xt=f.String,Nt=function(t){try{return xt(t)}catch(t){return'Object'}},_t=N,Dt=Nt,Rt=f.TypeError,It=function(t){if(_t(t))return t;throw Rt(Dt(t)+' is not a function')},Lt=It,Ct=function(t,e){var i=t[e];return null==i?void 0:Lt(i)},Ot=L,Bt=N,Vt=at,Mt=f.TypeError,Ft={exports:{}},Ut=f,jt=Object.defineProperty,qt=function(t,e){try{jt(Ut,t,{value:e,configurable:!0,writable:!0})}catch(i){Ut[t]=e}return e},Ht=f['__core-js_shared__']||qt('__core-js_shared__',{}),Gt=Ht;(Ft.exports=function(t,e){return Gt[t]||(Gt[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 Yt=Z,Qt=f.Object,zt=function(t){return Qt(Yt(t))},Wt=zt,Jt=x({}.hasOwnProperty),Kt=Object.hasOwn||function(t,e){return Jt(Wt(t),e)},Xt=x,Zt=0,te=Math.random(),ee=Xt(1..toString),ie=function(t){return'Symbol('+(void 0===t?'':t)+')_'+ee(++Zt+te,36)},se=f,ae=Ft.exports,re=Kt,oe=ie,ne=yt,ue=Tt,le=ae('wks'),de=se.Symbol,he=de&&de.for,ce=ue?de:de&&de.withoutSetter||oe,pe=function(t){if(!re(le,t)||!ne&&'string'!=typeof le[t]){var e='Symbol.'+t;ne&&re(de,t)?le[t]=de[t]:le[t]=ue&&he?he(e):ce(e)}return le[t]},me=L,fe=at,be=At,Se=Ct,ve=function(t,e){var i,s;if('string'===e&&Bt(i=t.toString)&&!Vt(s=Ot(i,t)))return s;if(Bt(i=t.valueOf)&&!Vt(s=Ot(i,t)))return s;if('string'!==e&&Bt(i=t.toString)&&!Vt(s=Ot(i,t)))return s;throw Mt('Can\'t convert object to primitive value')},ge=pe,ye=f.TypeError,Te=ge('toPrimitive'),Ee=function(t,e){if(!fe(t)||be(t))return t;var i,s=Se(t,Te);if(s){if(void 0===e&&(e='default'),i=me(s,t,e),!fe(i)||be(i))return i;throw ye('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),ve(t,e)},Pe=At,ke=function(t){var e=Ee(t,'string');return Pe(e)?e:e+''},we=at,$e=f.document,Ae=we($e)&&we($e.createElement),xe=function(t){return Ae?$e.createElement(t):{}},Ne=xe,_e=!D&&!b((function(){return 7!=Object.defineProperty(Ne('div'),'a',{get:function(){return 7}}).a})),De=D,Re=L,Ie=C,Le=U,Ce=it,Oe=ke,Be=Kt,Ve=_e,Me=Object.getOwnPropertyDescriptor;_.f=De?Me:function(t,e){if(t=Ce(t),e=Oe(e),Ve)try{return Me(t,e)}catch(t){}if(Be(t,e))return Le(!Re(Ie.f,t,e),t[e])};var Fe=b,Ue=N,je=/#|\.prototype\./,qe=function(t,e){var i=Ge[He(t)];return i==Qe||i!=Ye&&(Ue(e)?Fe(e):!!e)},He=qe.normalize=function(t){return String(t).replace(je,'.').toLowerCase()},Ge=qe.data={},Ye=qe.NATIVE='N',Qe=qe.POLYFILL='P',ze=qe,We=It,Je=S,Ke=x(x.bind),Xe=function(t,e){return We(t),void 0===e?t:Je?Ke(t,e):function(){return t.apply(e,arguments)}},Ze={},ti=D&&b((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ei=f,ii=at,si=ei.String,ai=ei.TypeError,ri=function(t){if(ii(t))return t;throw ai(si(t)+' is not an object')},oi=D,ni=_e,ui=ti,li=ri,di=ke,hi=f.TypeError,ci=Object.defineProperty,pi=Object.getOwnPropertyDescriptor;Ze.f=oi?ui?function(t,e,i){if(li(t),e=di(e),li(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=pi(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=di(e),li(i),ni)try{return ci(t,e,i)}catch(t){}if('get'in i||'set'in i)throw hi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var mi=Ze,fi=U,bi=D?function(t,e,i){return mi.f(t,e,fi(1,i))}:function(t,e,i){return t[e]=i,t},Si=f,vi=E,gi=x,yi=N,Ti=_.f,Ei=ze,Pi=rt,ki=Xe,wi=bi,$i=Kt,Ai=function(t){var e=function(i,s,a){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,a)}return vi(t,this,arguments)};return e.prototype=t.prototype,e},xi=function(t,e){var i,s,a,r,o,n,u,l,d=t.target,h=t.global,c=t.stat,p=t.proto,m=h?Si:c?Si[d]:(Si[d]||{}).prototype,f=h?Pi:Pi[d]||wi(Pi,d,{})[d],b=f.prototype;for(a in e)i=!Ei(h?a:d+(c?'.':'#')+a,t.forced)&&m&&$i(m,a),o=f[a],i&&(n=t.noTargetGet?(l=Ti(m,a))&&l.value:m[a]),r=i&&n?n:e[a],i&&typeof o==typeof r||(u=t.bind&&i?ki(r,Si):t.wrap&&i?Ai(r):p&&yi(r)?gi(r):r,(t.sham||r&&r.sham||o&&o.sham)&&wi(u,'sham',!0),wi(f,a,u),p&&($i(Pi,s=d+'Prototype')||wi(Pi,s,{}),wi(Pi[s],a,r),t.real&&b&&!b[a]&&wi(b,a,r)))},Ni=Math.ceil,_i=Math.floor,Di=function(t){var e=+t;return e!=e||0===e?0:(e>0?_i:Ni)(e)},Ri=Di,Ii=Math.min,Li=function(t){return t>0?Ii(Ri(t),9007199254740991):0},Ci=function(t){return Li(t.length)},Oi=zt,Bi=Ci,Vi=Di;xi({target:'Array',proto:!0},{at:function(t){var e=Oi(this),i=Bi(e),s=Vi(t),a=s>=0?s:i+s;return a<0||a>=i?void 0:e[a]}});var Mi,Fi,Ui,ji,qi=dt('Array','at');!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(Mi||(Mi={})),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'}(Fi||(Fi={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(Ui||(Ui={})),function(t){t.MP4='mp4',t.WEBM='webm'}(ji||(ji={}));var Hi=async t=>{const e=t.muted;try{await 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{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};const Gi=(e,i,s,{equal:a=((t,e)=>t===e),changed$:r,onError:o}={})=>{const n=e.getState(),u=i(),l=t.isNullable(r),d=new t.Subscription;return r&&d.add(r.subscribe((t=>{const i=e.getState();a(t,i)&&e.setState(t)}),o)),a(u,n)||(s(n),l&&e.setState(n)),d.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),l&&e.setState(t.to)}),o)),d},Yi=(e,i,s)=>Gi(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),Qi=(e,i,s,a)=>Gi(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:s,onError:a}),zi=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class Wi{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const a=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Gi(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(Gi(i.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(Gi(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);const a=t=>{var e,i,s,r,o;const n=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;n&&n.length&&(this.applyCueSettings(null!==(r=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==r?r:null),null===(o=t.target)||void 0===o||o.removeEventListener('cuechange',a))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',a)}))),this.subscription.add(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(Wi.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&zi(i,e)?i.mode='showing':i.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var Ji=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},Ki=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadeddata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());class Xi{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:a})=>{const r=s>=t&&s<e,o=a>=t&&a<e;r&&o||(r?i(e,a):o?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var Zi=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const o=t.start(r),n=t.end(r);if(o<=e&&e<=n){if(s=o,a=n,!i)return{start:s,end:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{start:s,end:a}},ts=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadedmetadata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());const es=e=>{const i=(i,s=(()=>{}))=>t.fromEvent(e,i).pipe(t.map(s)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((()=>e.readyState<3)),t.filterChanged()),a=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>Zi(e.buffered,e.currentTime)))),r=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),o=t.fromEvent(e,'error').pipe(t.map((()=>{const t=e.error;return{id:t?`MediaError#${t.code}`:'HtmlVideoError',message:t?t.message:'Error event from HTML video element'}}))),n=i('timeupdate',(()=>e.currentTime)),u=new t.Subject;let l;return n.subscribe((i=>{e.loop&&t.isNonNullable(l)&&t.isNonNullable(i)&&l>=e.duration-.3&&i<=.3&&u.next(l),l=i})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:u,error$:o,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:n,durationChange$:i('durationchange',(()=>e.duration)),isBuffering$:s,currentBuffer$:a,volumeState$:r,firstBytes$:ts(e),firstFrame$:Ki(e)}};var is;exports.VideoQuality=void 0,(is=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',is.Q_144P='144p',is.Q_240P='240p',is.Q_360P='360p',is.Q_480P='480p',is.Q_720P='720p',is.Q_1080P='1080p',is.Q_1440P='1440p',is.Q_2160P='2160p',is.Q_4320P='4320p';var ss=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},as=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const rs={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},os=(t,e)=>rs[t].height>rs[e].height,ns=(t,e)=>rs[t].height<rs[e].height,us=Object.keys(rs).sort(((t,e)=>ns(t,e)?-1:1)),ls=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return us.find((t=>{const e=rs[t];return e.width>=s&&e.height>=i}))},ds=t=>t===exports.VideoQuality.INVARIANT;let hs=!1,cs={};const ps=t=>{t(cs)},ms=(t,e)=>{var i;hs&&(cs.meta=null!==(i=cs.meta)&&void 0!==i?i:{},cs.meta[t]=e)};class fs{constructor(t){this.name=t}next(t){var e,i;if(!hs)return;cs.series=null!==(e=cs.series)&&void 0!==e?e:{};const s=null!==(i=cs.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),cs.series[this.name]=s}}const bs=new fs('best_bitrate'),Ss=(e,{container:i,throughput:s,tuning:a,limits:r,forwardBufferHealth:o,currentRepresentation:n})=>{var u,l,d,h;const c=a.usePixelRatio&&null!==(u=window.devicePixelRatio)&&void 0!==u?u:1,p=a.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*c*a.containerSizeFactor,height:i.height*c*a.containerSizeFactor},m=p&&ls(p),f=e.filter((t=>!ds(t.quality))).sort(((t,e)=>os(t.quality,e.quality)?-1:1)),b=null===(l=qi(f,-1))||void 0===l?void 0:l.quality,S=null===(d=qi(f,0))||void 0===d?void 0:d.quality,v=t.isNullable(r)||t.isNonNullable(r.min)&&t.isNonNullable(r.max)&&ns(r.max,r.min)||t.isNonNullable(r.min)&&S&&os(r.min,S)||t.isNonNullable(r.max)&&b&&ns(r.max,b),g=f.filter((e=>{var i;const u=!m||ns(e.quality,m),l=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s>=e.bitrate*(d=null!=o?o:.5,h=a.bitrateFactorAtEmptyBuffer,c=a.bitrateFactorAtFullBuffer,(h-c)*Math.pow(2,-10*d)+c);var d,h,c;const p=!a.lazyQualitySwitch||!n||(null!=o?o:.5)>=.5||((null===(i=e.size)||void 0===i?void 0:i.height)||0)<=((null==n?void 0:n.height)||0),f=v||(t.isNullable(r.max)||(b=e.quality,S=r.max,rs[b].height<=rs[S].height))&&(t.isNullable(r.min)||((t,e)=>rs[t].height>=rs[e].height)(e.quality,r.min));var b,S;return u&&l&&p&&f}))[0];return g&&g.bitrate&&bs.next(g.bitrate),null!==(h=null!=g?g:f[Math.ceil((f.length-1)/2)])&&void 0!==h?h:e[0]};var vs=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)},gs=t=>new URL(t).hostname;const ys=(e,i=300)=>new t.Observable((a=>{const{width:r,height:o}=e.getBoundingClientRect();if(a.next({width:r,height:o}),!window.ResizeObserver)return;const n=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,r;i.contentBoxSize&&i.contentBoxSize[0]?(r=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,r=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(r)&&a.next({width:s,height:r})}),i));return n.observe(e),()=>n.disconnect()}));class Ts{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var Es={};function Ps(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function ks(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 ws(t,e,i){return e&&ks(t.prototype,e),i&&ks(t,i),t}function $s(t){return($s=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function As(t,e){return(As=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function xs(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function Ns(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?xs(t):e}function _s(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=$s(t);if(e){var a=$s(this).constructor;i=Reflect.construct(s,arguments,a)}else i=s.apply(this,arguments);return Ns(this,i)}}function Ds(t,e,i){return(Ds='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=$s(t)););return t}(t,e);if(s){var a=Object.getOwnPropertyDescriptor(s,e);return a.get?a.get.call(i):a.value}})(t,e,i||t)}Object.defineProperty(Es,'__esModule',{value:!0});var Rs=function(){function t(){Ps(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return ws(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,a=i.length;s<a;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 a=e[i];try{a.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}a.options&&a.options.once&&this.removeEventListener(t.type,a.callback)}return!t.defaultPrevented}}}]),t}(),Is=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&&As(t,e)}(i,Rs);var e=_s(i);function i(){var t;return Ps(this,i),(t=e.call(this)).listeners||Rs.call(xs(t)),Object.defineProperty(xs(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(xs(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return ws(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)),Ds($s(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),Ls=function(){function t(){Ps(this,t),Object.defineProperty(this,'signal',{value:new Is,writable:!0,configurable:!0})}return ws(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&&(Ls.prototype[Symbol.toStringTag]='AbortController',Is.prototype[Symbol.toStringTag]='AbortSignal');var Cs=Es.AbortController=Ls;Es.AbortSignal=Is;var Os=Es.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e=t,i=e.fetch,s=e.Request,a=void 0===s?i.Request:s,r=e.AbortController,o=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,n=void 0!==o&&o;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:a,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:n}))return{fetch:i,Request:u};var u=a;(u&&!u.prototype.hasOwnProperty('signal')||n)&&((u=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var s=new a(t,e);return i&&Object.defineProperty(s,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),s}).prototype=a.prototype);var l=i;return{fetch:function(t,e){var i=u&&u.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 a=new Promise((function(t,e){i.addEventListener('abort',(function(){return e(s)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,l(t,e)])}return l(t,e)},Request:u}},Bs={},Vs=N,Ms=Ht,Fs=x(Function.toString);Vs(Ms.inspectSource)||(Ms.inspectSource=function(t){return Fs(t)});var Us,js,qs,Hs=N,Gs=Ms.inspectSource,Ys=f.WeakMap,Qs=Hs(Ys)&&/native code/.test(Gs(Ys)),zs=Ft.exports,Ws=ie,Js=zs('keys'),Ks=function(t){return Js[t]||(Js[t]=Ws(t))},Xs={},Zs=Qs,ta=f,ea=x,ia=at,sa=bi,aa=Kt,ra=Ht,oa=Ks,na=Xs,ua=ta.TypeError,la=ta.WeakMap;if(Zs||ra.state){var da=ra.state||(ra.state=new la),ha=ea(da.get),ca=ea(da.has),pa=ea(da.set);Us=function(t,e){if(ca(da,t))throw new ua('Object already initialized');return e.facade=t,pa(da,t,e),e},js=function(t){return ha(da,t)||{}},qs=function(t){return ca(da,t)}}else{var ma=oa('state');na[ma]=!0,Us=function(t,e){if(aa(t,ma))throw new ua('Object already initialized');return e.facade=t,sa(t,ma,e),e},js=function(t){return aa(t,ma)?t[ma]:{}},qs=function(t){return aa(t,ma)}}var fa={set:Us,get:js,has:qs,enforce:function(t){return qs(t)?js(t):Us(t,{})},getterFor:function(t){return function(e){var i;if(!ia(e)||(i=js(e)).type!==t)throw ua('Incompatible receiver, '+t+' required');return i}}},ba=D,Sa=Kt,va=Function.prototype,ga=ba&&Object.getOwnPropertyDescriptor,ya=Sa(va,'name'),Ta={EXISTS:ya,PROPER:ya&&'something'===function(){}.name,CONFIGURABLE:ya&&(!ba||ba&&ga(va,'name').configurable)},Ea={},Pa=Di,ka=Math.max,wa=Math.min,$a=it,Aa=function(t,e){var i=Pa(t);return i<0?ka(i+e,0):wa(i,e)},xa=Ci,Na=function(t){return function(e,i,s){var a,r=$a(e),o=xa(r),n=Aa(s,o);if(t&&i!=i){for(;o>n;)if((a=r[n++])!=a)return!0}else for(;o>n;n++)if((t||n in r)&&r[n]===i)return t||n||0;return!t&&-1}},_a={includes:Na(!0),indexOf:Na(!1)},Da=Kt,Ra=it,Ia=_a.indexOf,La=Xs,Ca=x([].push),Oa=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Ba=function(t,e){var i,s=Ra(t),a=0,r=[];for(i in s)!Da(La,i)&&Da(s,i)&&Ca(r,i);for(;e.length>a;)Da(s,i=e[a++])&&(~Ia(r,i)||Ca(r,i));return r},Va=Oa,Ma=Object.keys||function(t){return Ba(t,Va)},Fa=D,Ua=ti,ja=Ze,qa=ri,Ha=it,Ga=Ma;Ea.f=Fa&&!Ua?Object.defineProperties:function(t,e){qa(t);for(var i,s=Ha(e),a=Ga(e),r=a.length,o=0;r>o;)ja.f(t,i=a[o++],s[i]);return t};var Ya,Qa=dt('document','documentElement'),za=ri,Wa=Ea,Ja=Oa,Ka=Xs,Xa=Qa,Za=xe,tr=Ks('IE_PROTO'),er=function(){},ir=function(t){return'<script>'+t+'<\/script>'},sr=function(t){t.write(ir('')),t.close();var e=t.parentWindow.Object;return t=null,e},ar=function(){try{Ya=new ActiveXObject('htmlfile')}catch(t){}var t,e;ar='undefined'!=typeof document?document.domain&&Ya?sr(Ya):((e=Za('iframe')).style.display='none',Xa.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(ir('document.F=Object')),t.close(),t.F):sr(Ya);for(var i=Ja.length;i--;)delete ar.prototype[Ja[i]];return ar()};Ka[tr]=!0;var rr,or,nr,ur=Object.create||function(t,e){var i;return null!==t?(er.prototype=za(t),i=new er,er.prototype=null,i[tr]=t):i=ar(),void 0===e?i:Wa.f(i,e)},lr=!b((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),dr=f,hr=Kt,cr=N,pr=zt,mr=lr,fr=Ks('IE_PROTO'),br=dr.Object,Sr=br.prototype,vr=mr?br.getPrototypeOf:function(t){var e=pr(t);if(hr(e,fr))return e[fr];var i=e.constructor;return cr(i)&&e instanceof i?i.prototype:e instanceof br?Sr:null},gr=bi,yr=function(t,e,i,s){s&&s.enumerable?t[e]=i:gr(t,e,i)},Tr=b,Er=N,Pr=ur,kr=vr,wr=yr,$r=pe('iterator'),Ar=!1;[].keys&&('next'in(nr=[].keys())?(or=kr(kr(nr)))!==Object.prototype&&(rr=or):Ar=!0);var xr=null==rr||Tr((function(){var t={};return rr[$r].call(t)!==t}));Er((rr=xr?{}:Pr(rr))[$r])||wr(rr,$r,(function(){return this}));var Nr={IteratorPrototype:rr,BUGGY_SAFARI_ITERATORS:Ar},_r={};_r[pe('toStringTag')]='z';var Dr='[object z]'===String(_r),Rr=f,Ir=Dr,Lr=N,Cr=G,Or=pe('toStringTag'),Br=Rr.Object,Vr='Arguments'==Cr(function(){return arguments}()),Mr=Ir?Cr: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=Br(t),Or))?i:Vr?Cr(e):'Object'==(s=Cr(e))&&Lr(e.callee)?'Arguments':s},Fr=Mr,Ur=Dr?{}.toString:function(){return'[object '+Fr(this)+']'},jr=Dr,qr=Ze.f,Hr=bi,Gr=Kt,Yr=Ur,Qr=pe('toStringTag'),zr=function(t,e,i,s){if(t){var a=i?t:t.prototype;Gr(a,Qr)||qr(a,Qr,{configurable:!0,value:e}),s&&!jr&&Hr(a,'toString',Yr)}},Wr=Nr.IteratorPrototype,Jr=ur,Kr=U,Xr=zr,Zr=Bs,to=function(){return this},eo=f,io=(eo.String,eo.TypeError,x);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=io(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var so=xi,ao=L,ro=function(t,e,i,s){var a=e+' Iterator';return t.prototype=Jr(Wr,{next:Kr(+!s,i)}),Xr(t,a,!1,!0),Zr[a]=to,t},oo=vr,no=zr,uo=yr,lo=Bs,ho=Ta.PROPER,co=Nr.BUGGY_SAFARI_ITERATORS,po=pe('iterator'),mo=function(){return this},fo=it,bo=Bs,So=fa;Ze.f;var vo=function(t,e,i,s,a,r,o){ro(i,e,s);var n,u,l,d=function(t){if(t===a&&f)return f;if(!co&&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)}},h=e+' Iterator',c=!1,p=t.prototype,m=p[po]||p['@@iterator']||a&&p[a],f=!co&&m||d(a),b='Array'==e&&p.entries||m;if(b&&(n=oo(b.call(new t)))!==Object.prototype&&n.next&&(no(n,h,!0,!0),lo[h]=mo),ho&&'values'==a&&m&&'values'!==m.name&&(c=!0,f=function(){return ao(m,this)}),a)if(u={values:d('values'),keys:r?f:d('keys'),entries:d('entries')},o)for(l in u)(co||c||!(l in p))&&uo(p,l,u[l]);else so({target:e,proto:!0,forced:co||c},u);return o&&p[po]!==f&&uo(p,po,f,{name:a}),lo[e]=f,u},go=So.set,yo=So.getterFor('Array Iterator');vo(Array,'Array',(function(t,e){go(this,{type:'Array Iterator',target:fo(t),index:0,kind:e})}),(function(){var t=yo(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'),bo.Arguments=bo.Array;var To=Bs,Eo=pe('iterator'),Po=Array.prototype,ko=Mr,wo=Ct,$o=Bs,Ao=pe('iterator'),xo=function(t){if(null!=t)return wo(t,Ao)||wo(t,'@@iterator')||$o[ko(t)]},No=L,_o=It,Do=ri,Ro=Nt,Io=xo,Lo=f.TypeError,Co=L,Oo=ri,Bo=Ct,Vo=Xe,Mo=L,Fo=ri,Uo=Nt,jo=function(t){return void 0!==t&&(To.Array===t||Po[Eo]===t)},qo=Ci,Ho=ht,Go=function(t,e){var i=arguments.length<2?Io(t):e;if(_o(i))return Do(No(i,t));throw Lo(Ro(t)+' is not iterable')},Yo=xo,Qo=function(t,e,i){var s,a;Oo(t);try{if(!(s=Bo(t,'return'))){if('throw'===e)throw i;return i}s=Co(s,t)}catch(t){a=!0,s=t}if('throw'===e)throw i;if(a)throw s;return Oo(s),i},zo=f.TypeError,Wo=function(t,e){this.stopped=t,this.result=e},Jo=Wo.prototype,Ko=ke,Xo=Ze,Zo=U,tn=function(t,e,i){var s,a,r,o,n,u,l,d=i&&i.that,h=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=Vo(e,d),f=function(t){return s&&Qo(s,'normal',t),new Wo(!0,t)},b=function(t){return h?(Fo(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(c)s=t;else{if(!(a=Yo(t)))throw zo(Uo(t)+' is not iterable');if(jo(a)){for(r=0,o=qo(t);o>r;r++)if((n=b(t[r]))&&Ho(Jo,n))return n;return new Wo(!1)}s=Go(t,a)}for(u=s.next;!(l=Mo(u,s)).done;){try{n=b(l.value)}catch(t){Qo(s,'throw',t)}if('object'==typeof n&&n&&Ho(Jo,n))return n}return new Wo(!1)},en=function(t,e,i){var s=Ko(e);s in t?Xo.f(t,s,Zo(0,i)):t[s]=i};xi({target:'Object',stat:!0},{fromEntries:function(t){var e={};return tn(t,(function(t,i){en(e,t,i)}),{AS_ENTRIES:!0}),e}});var sn=rt.Object.fromEntries,an={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},rn=f,on=Mr,nn=bi,un=Bs,ln=pe('toStringTag');for(var dn in an){var hn=rn[dn],cn=hn&&hn.prototype;cn&&on(cn)!==ln&&nn(cn,ln,dn),un[dn]=un.Array}var pn,mn=sn,fn=t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e},bn=t=>{const e=new URL(t);return e.searchParams.append('quic','1'),e.toString()},Sn=t=>{var e,i;const s=t.get('X-Delivery-Type'),a=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===a?void 0:null!==(i={1:!0,0:!1}[a])&&void 0!==i?i:void 0}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pn||(pn={}));class vn{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new Cs,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=bn(e));const i=yield Os(fetch).fetch(e,{signal:this.abortAllController.signal}).catch(gn);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetchRange=t.abortable(this.abortAllController.signal,async function*(e,i,s,{method:a=pn.HEADER,onProgress:r,signal:o}={}){var n,u,l;let d=e;const h=new Headers;switch(a){case pn.HEADER:h.append('Range',`${i}-${s}`);break;case pn.PARAM:{const t=new URL(d,location.href);t.searchParams.append('bytes',`${i}-${s}`),d=t.toString();break}default:t.assertNever(a)}this.requestQuic&&(d=bn(d));let c=this.abortAllController.signal;if(o){const e=new Cs;this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(o,'abort')).subscribe((()=>{e.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&e.abort(),c=e.signal}const p=t.now(),m=yield Os(fetch).fetch(d,{headers:h,signal:c}).catch(gn);if(null===(n=this.throughputEstimator)||void 0===n||n.addRawRtt(t.now()-p),!m)return null;if(!m.ok||!m.body)return Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));this.onHeadersReceived(m.headers);const[f,b]=m.body.tee(),S=f.getReader();null===(u=this.throughputEstimator)||void 0===u||u.trackStream(b);const v=parseInt(null!==(l=m.headers.get('Content-Length'))&&void 0!==l?l:'',10);let g=0;const y=new ArrayBuffer(v),T=new Uint8Array(y),E=new DataView(y);let P=!1;const k=t=>{P=!0,gn(t)},w=t.abortable(this.abortAllController.signal,async function*({done:e,value:i}){0===g&&this.lastRequestFirstBytes$.next(t.now()-p),e?null==r||r(E,g):i&&(T.set(i,g),g+=i.byteLength,null==r||r(E,g),yield null==S?void 0:S.read().then(w,k))}.bind(this));return yield null==S?void 0:S.read().then(w,k),P?null:y}.bind(this)),this.fetchRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e,i=0){const{from:s,to:a}=t.initRange;let r,o,n=s,u=a,l=!1;t.indexRange&&(r=t.indexRange.from,o=t.indexRange.to,l=a+1===r,l&&(n=Math.min(r,s),u=Math.max(o,a))),n=Math.min(n,0),u+=i;const d=yield this.fetchRange(t.url,n,u,{method:pn.PARAM});if(!d)return null;const h=new DataView(d,s-n,a-n+1);if(!e.validateData(h))throw new Error('Invalid media file');const c=e.parseInit(h);let p;if(l&&void 0!==r&&void 0!==o)p=new DataView(d,r-n,o-r+1);else{const i=e.getIndexRange(c);if(i){const e=yield this.fetchRange(t.url,i.from,i.to,{method:pn.PARAM});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,c);return{dataView:new DataView(d),segments:m}}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=Sn(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const gn=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},yn=new TextDecoder('ascii'),Tn=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=yn.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},En={validateData:t=>'ftyp'===yn.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Tn(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),o=a(),n=a(),u=255&a();let l=o/r*1e3,d=t.byteOffset+t.byteLength+n;for(let t=0;t<u;t++){const t=a(),e=t>>>31,s=t<<1>>>1,o=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const n=o/r*1e3;i.push({status:Ui.NONE,time:{from:l,to:l+n},byte:{from:d,to:d+s-1}}),l+=n,d+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=Tn(a);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Pn,kn;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(Pn||(Pn={})),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'}(kn||(kn={}));const wn={[Pn.EBML]:{type:kn.Master},[Pn.EBMLVersion]:{type:kn.UnsignedInteger},[Pn.EBMLReadVersion]:{type:kn.UnsignedInteger},[Pn.EBMLMaxIDLength]:{type:kn.UnsignedInteger},[Pn.EBMLMaxSizeLength]:{type:kn.UnsignedInteger},[Pn.DocType]:{type:kn.String},[Pn.DocTypeVersion]:{type:kn.UnsignedInteger},[Pn.DocTypeReadVersion]:{type:kn.UnsignedInteger},[Pn.Void]:{type:kn.Binary},[Pn.Segment]:{type:kn.Master},[Pn.SeekHead]:{type:kn.Master},[Pn.Seek]:{type:kn.Master},[Pn.SeekID]:{type:kn.Binary},[Pn.SeekPosition]:{type:kn.UnsignedInteger},[Pn.Info]:{type:kn.Master},[Pn.TimestampScale]:{type:kn.UnsignedInteger},[Pn.Duration]:{type:kn.Float},[Pn.Tracks]:{type:kn.Master},[Pn.Chapters]:{type:kn.Master},[Pn.Cluster]:{type:kn.Master},[Pn.Timestamp]:{type:kn.UnsignedInteger},[Pn.SilentTracks]:{type:kn.Master},[Pn.SilentTrackNumber]:{type:kn.UnsignedInteger},[Pn.Position]:{type:kn.UnsignedInteger},[Pn.PrevSize]:{type:kn.UnsignedInteger},[Pn.SimpleBlock]:{type:kn.Binary},[Pn.BlockGroup]:{type:kn.Master},[Pn.EncryptedBlock]:{type:kn.Binary},[Pn.Attachments]:{type:kn.Master},[Pn.Tags]:{type:kn.Master},[Pn.Cues]:{type:kn.Master},[Pn.CuePoint]:{type:kn.Master},[Pn.CueTime]:{type:kn.UnsignedInteger},[Pn.CueTrackPositions]:{type:kn.Master},[Pn.CueTrack]:{type:kn.UnsignedInteger},[Pn.CueClusterPosition]:{type:kn.UnsignedInteger},[Pn.CueRelativePosition]:{type:kn.UnsignedInteger},[Pn.CueDuration]:{type:kn.UnsignedInteger},[Pn.CueBlockNumber]:{type:kn.UnsignedInteger},[Pn.CueCodecState]:{type:kn.UnsignedInteger},[Pn.CueReference]:{type:kn.Master},[Pn.CueRefTime]:{type:kn.UnsignedInteger}},$n=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=An(t,i),a=s in wn,r=a?wn[s].type:kn.Binary,o=t.getUint8(i);let n=0;128&o?n=1:64&o?n=2:32&o?n=3:16&o?n=4:8&o?n=5:4&o?n=6:2&o?n=7:1&o&&(n=8);const u=new DataView(t.buffer,t.byteOffset+i+1,n-1),l=((o&255>>n)<<8*(n-1))+An(u),d=i+n;let h;return h=d+l>t.byteLength?new DataView(t.buffer,t.byteOffset+d):new DataView(t.buffer,t.byteOffset+d,l),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:d,tagSize:d+l,value:h,valueSize:l}},An=(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},xn=(e,i)=>{switch(i){case kn.SignedInteger:return e.getInt8(0);case kn.UnsignedInteger:return An(e);case kn.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case kn.String:return new TextDecoder('ascii').decode(e);case kn.UTF8:return new TextDecoder('utf-8').decode(e);case kn.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case kn.Master:case kn.Binary:return e;default:t.assertNever(i)}},Nn=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=$n(s);if(!e(a))return;a.type===kn.Master&&Nn(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},_n=[Pn.Info,Pn.SeekHead,Pn.Tracks,Pn.Chapters,Pn.Cluster,Pn.Cues,Pn.Attachments,Pn.Tags],Dn=[Pn.Timestamp,Pn.SilentTracks,Pn.SilentTrackNumber,Pn.Position,Pn.PrevSize,Pn.SimpleBlock,Pn.BlockGroup,Pn.EncryptedBlock],Rn={validateData:t=>{if(t.getUint32(0)!==Pn.EBML)return!1;let e,i,s;const a=$n(t);return Nn(a.value,(({tag:t,type:a,value:r})=>(t===Pn.EBMLReadVersion?e=xn(r,a):t===Pn.DocType?i=xn(r,a):t===Pn.DocTypeReadVersion&&(s=xn(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,a,r,o,n,u=!1,l=!1,d=!1;return Nn(e,(({tag:t,type:e,value:h,valueSize:c})=>{if(t===Pn.SeekID){const t=xn(h,e);n=An(t)}else t!==Pn.SeekPosition&&(n=void 0);return t===Pn.Segment?(i=h.byteOffset,s=h.byteOffset+c):t===Pn.Info?u=!0:t===Pn.SeekHead?l=!0:t===Pn.TimestampScale?a=xn(h,e):t===Pn.Duration?r=xn(h,e):t===Pn.SeekPosition&&n===Pn.Cues?o=xn(h,e):u&&l&&_n.includes(t)&&(d=!0),!d})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(r,'Failed to parse webm Segment duration'),a=null!=a?a:1e6,{segmentStart:Math.round(i/1e9*a*1e3),segmentEnd:Math.round(s/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:o}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,a=!1;const r=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),o=[];let n;return Nn(e,(({tag:t,type:e,value:i})=>{switch(t){case Pn.Cues:s=!0;break;case Pn.CuePoint:n&&r(n)&&o.push(n),n={};break;case Pn.CueTime:n&&(n.time=xn(i,e));break;case Pn.CueTrackPositions:break;case Pn.CueClusterPosition:n&&(n.position=xn(i,e));break;default:s&&_n.includes(t)&&(a=!0)}return!(s&&a)})),n&&r(n)&&o.push(n),o.map(((t,e)=>{const{time:s,position:a}=t,r=o[e+1];return{status:Ui.NONE,time:{from:s,to:r?r.time:i.segmentDuration},byte:{from:i.segmentStart+a,to:r?i.segmentStart+r.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Nn(t,(s=>s.tag===Pn.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Dn.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Pn.SimpleBlock,Pn.BlockGroup,Pn.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class In{constructor(e,i,s,a,{fetcher:r,tuning:o,getCurrentPosition:n}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.activeSegments=new Set,this.downloadAbortController=new Cs,this.destroyAbortController=new Cs,this.allInitsLoaded=!1,this.bufferUpdateQueue=[],this.bufferUpdateQueueInProgress=!1,this.bufferLimit=1/0,this.startWith=t.abortable(this.destroyAbortController.signal,async function*(e){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const s=yield this.fetcher.fetchRepresentation(i,this.containerParser).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:a,segments:r}=s,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e,o),yield this.appendDataToBuffer(o,this.destroyAbortController.signal),this.segments.set(e,r)}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,async function*(e){var i;if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=e,!this.initData.has(e))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const i=this.representations.get(e);t.assertNonNullable(i);const s=yield this.fetcher.fetchRepresentation(i,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:a,segments:r}=s,o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e,o),this.segments.set(e,r)}const s=this.initData.get(e);t.assertNonNullable(s,`No init buffer for ${e}`),t.assertNonNullable(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.appendDataToBuffer(s,this.downloadAbortController.signal),t.isNonNullable(this.playingRepresentationId)&&(null===(i=this.segments.get(this.playingRepresentationId))||void 0===i||i.forEach((t=>{t.status!==Ui.FED&&t.status!==Ui.PARTIALLY_FED||(t.status=Ui.NONE)})));const a=this.getCurrentPosition();t.isNonNullable(a)&&this.maintain(a)}.bind(this)),this.fetcher=r,this.tuning=o,this.getCurrentPosition=n,this.container=s,s){case ji.MP4:this.containerParser=En;break;case ji.WEBM:this.containerParser=Rn;break;default:t.assertNever(s)}this.initData=new Map,this.segments=new Map,this.representations=new Map(a.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}abort(){this.downloadAbortController.abort(),this.downloadAbortController=new Cs,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer)||this.onLastSegment$.getValue())return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);t.assertNonNullable(i),t.assertNonNullable(s);const a=s.find((t=>e>=t.time.from&&e<t.time.to));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=vs(this.sourceBuffer.buffered,e);r=e+Math.min(t,this.tuning.representationSwitchForwardBufferGap)}let o=[];isFinite(this.bufferLimit)&&fn(this.sourceBuffer.buffered)>=.8*this.bufferLimit?this.pruneBuffer(1/0):(o=this.selectForwardBufferSegments(s,r),o.length&&this.loadSegments(o,i)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&a&&a.status===Ui.FED&&!o.length&&vs(this.sourceBuffer.buffered,e)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const n=qi(s,-1);n&&n.status===Ui.FED&&(this.fullyBuffered$.next(!0),a===n&&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.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===Ui.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.forwardBufferTarget));if(-1===i)return[];let s=0;const a=[];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!==Ui.NONE)break;a.push(i)}return a}async loadSegments(e,i){if(!e.length)return;const s=qi(e,0).byte.from,a=qi(e,-1).byte.to;for(const t of e)t.status=Ui.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,fedBytes:0});const{signal:r}=this.downloadAbortController;return this.segmentDownloadPromise=this.segmentDownloadPromise.then(t.abortable(this.destroyAbortController.signal,async function*(){if(r.aborted)for(const t of e)t.status===Ui.DOWNLOADING&&(t.status=Ui.NONE);else yield this.fetcher.fetchRange(i.url,s,a,{method:pn.PARAM,onProgress:(t,e)=>this.onSomeDataLoaded(t,i.id,s,e,r),signal:r})}.bind(this))).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}async onSomeDataLoaded(t,e,i,s,a){var r;if(!this.activeSegments.size)return;const o=t=>{t.segment.status=Ui.NONE,this.activeSegments.delete(t)},n=t=>{this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=Ui.FED,this.activeSegments.delete(t),requestIdleCallback((()=>this.detectGaps(e,[t.segment])))};for(const e of this.activeSegments){const{segment:u}=e,l=u.byte.to-u.byte.from+1;if(a.aborted)return void o(e);const d=u.byte.from>=i,h=u.byte.from<i+s,c=u.byte.to<=i+s;if(u.status===Ui.DOWNLOADING&&d&&h&&c){u.status=Ui.DOWNLOADED,this.activeSegments.delete(e);const r=new DataView(t.buffer,t.byteOffset+u.byte.from-i,Math.min(l,i+s-u.byte.from));this.appendDataToBuffer(r,a).then((t=>t&&!a.aborted?n(e):o(e)))}else if(this.tuning.enableSubSegmentBufferFeeding&&d&&h){const d=Math.min(l,s-(u.byte.from-i));e.buffer=null!==(r=e.buffer)&&void 0!==r?r:new ArrayBuffer(l);const h=new DataView(e.buffer);for(let e=0;e<d;e++)h.setUint8(e,t.getUint8(u.byte.from-i+e));e.loadedBytes=d;const c=new DataView(e.buffer,e.fedBytes,e.loadedBytes-e.fedBytes);if(l===e.loadedBytes&&e.fedBytes!==e.loadedBytes)e.fedBytes=e.loadedBytes,this.appendDataToBuffer(c,a).then((t=>t&&!a.aborted?n(e):o(e)));else if(e.loadedBytes>e.fedBytes){const t=this.containerParser.parseFeedableSegmentChunk(c);t&&(u.status=Ui.PARTIALLY_FED,e.fedBytes+=t.byteLength,this.appendDataToBuffer(t,a).then((t=>{!t||a.aborted?o(e):e.fedBytes===l&&n(e)})))}}}}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=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,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t,a),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async appendDataToBuffer(e,i){if(t.assertNonNullable(this.sourceBuffer),i&&i.aborted)return!1;if(!this.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;const s=()=>{if(this.bufferUpdateQueueInProgress)return;this.bufferUpdateQueueInProgress=!0;const t=this.bufferUpdateQueue[0];if(!t)return void(this.bufferUpdateQueueInProgress=!1);const{data:e,callback:i}=t;if(!this.sourceBuffer)return this.bufferUpdateQueueInProgress=!1,void i(!1);try{this.sourceBuffer.appendBuffer(e)}catch(t){return t instanceof DOMException&&'QuotaExceededError'===t.name?(this.bufferLimit=Math.min(this.bufferLimit,.9*fn(this.sourceBuffer.buffered)),void this.pruneBuffer(e.byteLength).then((t=>{t?(this.bufferUpdateQueueInProgress=!1,s()):(this.bufferUpdateQueueInProgress=!1,this.bufferUpdateQueue.shift(),i(!1))}),(()=>{this.error$.next({id:'PruneBuffer',message:'Error trying to clean buffer',thrown:t})}))):(this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),this.bufferUpdateQueueInProgress=!1,this.bufferUpdateQueue.shift(),void i(!1))}In.waitForBufferUpdate(this.sourceBuffer).then((()=>{this.bufferUpdateQueueInProgress=!1,this.bufferUpdateQueue.shift(),i(!0),s()}))};return new Promise((t=>{this.bufferUpdateQueue.push({data:e,callback:t}),this.sourceBuffer?this.sourceBuffer.updating?In.waitForBufferUpdate(this.sourceBuffer).then(s):s():t(!1)}))}async pruneBuffer(e){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let a=0,r=1/0,o=-1/0,n=!1;for(const t of s){if(t.time.to>=i||a>=e)break;t.status===Ui.FED&&(r=Math.min(r,t.time.from),o=Math.max(o,t.time.to),a+=t.byte.to-t.byte.from)}if(n=isFinite(r)&&isFinite(o)&&(a>=e||e===1/0),!n){a=0,r=1/0,o=-1/0;for(const t of s)t.status===Ui.FED&&t.time.from>i+this.tuning.forwardBufferTarget&&(r=Math.min(r,t.time.from),o=Math.max(o,t.time.to),a+=t.byte.to-t.byte.from)}return n=isFinite(r)&&isFinite(o)&&(a>=e||e===1/0),!!n&&(this.sourceBuffer.remove(r/1e3,o/1e3),await In.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})}}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=this.segments.get(this.playingRepresentationId);if(t.isNullable(e))return;const i=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=this.sourceBuffer.buffered.end(t),a=1e3*(s%1>.9?Math.round(s):s);i.push({from:e,to:a})}for(const t of e){const e=i.some((e=>e.from<=t.time.from&&e.to>=t.time.to));t.status!==Ui.FED||e||(t.status=Ui.NONE)}}static async waitForBufferUpdate(t){return new Promise((e=>{if(t){const i=()=>{e(),t.removeEventListener('updateend',i)};t.addEventListener('updateend',i)}else e()}))}}const Ln=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},Cn=['timeupdate','progress','play','seeked','stalled'];var On,Bn;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(On||(On={}));class Vn{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new Ts(On.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Cs,this.initManifest=t.abortable(this.destroyController.signal,async function*(e,i){this.element=e,this.state$.startTransitionTo(On.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i);if(!s)return null;let a;try{a=((t,e)=>{var i,s,a,r,o,n,u,l,d,h,c,p,m,f,b,S,v,g,y,T,E,P,k,w;const $={video:[],audio:[],text:[]},A=(new DOMParser).parseFromString(t,'application/xml').children[0],x=A.getElementsByTagName('Period')[0].children;let N=0;const _=null!==(s=null===(i=A.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==s?s:[],D=_.includes(Fi.WEBM_AS_IN_FFMPEG)||_.includes(Fi.WEBM_AS_IN_SPEC)?ji.WEBM:ji.MP4;for(const t of x){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),A=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==i?void 0:i.split('/')[0],x=null!==(o=null===(r=t.getAttribute('profiles'))||void 0===r?void 0:r.split(','))&&void 0!==o?o:[],D=t.querySelectorAll('Representation');for(const a of D){const r=null!==(n=a.getAttribute('mimeType'))&&void 0!==n?n:i,o=null!==(l=null!==(u=a.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==l?l:'',D=null!==(h=null!==(d=a.getAttribute('contentType'))&&void 0!==d?d:null==r?void 0:r.split('/')[0])&&void 0!==h?h:A,R=null!==(p=null===(c=t.getAttribute('profiles'))||void 0===c?void 0:c.split(','))&&void 0!==p?p:[],I=parseInt(null!==(m=a.getAttribute('width'))&&void 0!==m?m:'',10),L=parseInt(null!==(f=a.getAttribute('height'))&&void 0!==f?f:'',10),C=parseInt(null!==(b=a.getAttribute('bandwidth'))&&void 0!==b?b:'',10)/1e3,O=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',B=null!==(v=a.getAttribute('quality'))&&void 0!==v?v:void 0,V=O?Ln(O):void 0,M=`${null!==(g=a.getAttribute('id'))&&void 0!==g?g:(N++).toString(10)}@${'video'===D?`${L}p`:'audio'===D?`${C}Kbps`:o}`,F=null!==(E=null===(T=null===(y=a.querySelector('BaseURL'))||void 0===y?void 0:y.textContent)||void 0===T?void 0:T.trim())&&void 0!==E?E:'',U=new URL(F,e).toString(),j=[..._,...x,...R],q=null!==(k=null===(P=a.querySelector('SegmentBase Initialization'))||void 0===P?void 0:P.getAttribute('range'))&&void 0!==k?k:'',[H,G]=q.split('-').map((t=>parseInt(t,10))),Y={from:H,to:G},Q=null===(w=a.querySelector('SegmentBase'))||void 0===w?void 0:w.getAttribute('indexRange'),[z,W]=Q?Q.split('-').map((t=>parseInt(t,10))):[],J=Q?{from:z,to:W}:void 0;if(!D||!r)continue;const K={video:Mi.VIDEO,audio:Mi.AUDIO,text:Mi.TEXT}[D];K&&$[K].push({id:M,kind:K,profiles:j,initRange:Y,indexRange:J,bitrate:C,mime:r,codecs:o,width:I,height:L,fps:V,quality:B,url:U})}}return{container:D,representations:$}})(null!=s?s:'',i)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}t.assertNonNullable(a);const r=({mime:t,codecs:i})=>{var s,a,r;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(r=null===(a=window.MediaSource)||void 0===a?void 0:a.isTypeSupported)||void 0===r?void 0:r.call(a,`${t}; codecs="${i}"`)))};return this.manifest={...a,representations:mn(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(On.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,async function*(e,i){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(On.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning.dash,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new In(Mi.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.audioBufferManager=new In(Mi.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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(t.merge(this.forceEnded$,t.merge(this.videoBufferManager.onLastSegment$,this.audioBufferManager.onLastSegment$,this.videoBufferManager.fullyBuffered$,this.audioBufferManager.fullyBuffered$).pipe(t.filter((()=>!(!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;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(t.merge(this.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(e),this.audioBufferManager.startWith(i)]),this.state$.setState(On.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...Cn.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{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()}.bind(this)),this.tick=()=>{if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const e=1e3*this.element.currentTime;this.videoBufferManager.maintain(e),this.audioBufferManager.maintain(e),!this.videoBufferManager.gaps.length&&!this.audioBufferManager.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new vn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(e,i){const s={[Mi.VIDEO]:this.videoBufferManager,[Mi.AUDIO]:this.audioBufferManager,[Mi.TEXT]:null}[e];return t.assertNonNullable(s),s.switchTo(i)}seek(e){t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),t.assertNonNullable(this.audioBufferManager),this.videoBufferManager.abort(),this.audioBufferManager.abort(),this.videoBufferManager.maintain(e),this.audioBufferManager.maintain(e),this.element.currentTime=e/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(On.NONE)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of[this.videoBufferManager,this.audioBufferManager])for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Bn||(Bn={}));const Mn=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{var o;const n=null!==(o=r?ss(r):void 0)&&void 0!==o?o:ls({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Fn=(t,e,i)=>{var s;const a=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return null!==(s=qi(t,Math.round(t.length*a/e.length)))&&void 0!==s?s:qi(t,-1)};class Un{constructor(e){this.subscription=new t.Subscription,this.videoState=new Ts(Bn.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Wi,this.videoTracks=[],this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const r=null==a?void 0:a.to;if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(r)&&e!==Bn.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(r),i!==exports.PlaybackState.STOPPED){if(e===Bn.STOPPED)return this.videoState.startTransitionTo(Bn.READY),void this.prepare();switch(e){case Bn.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Bn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Bn.PLAYING),this.playIfAllowed()));case Bn.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Bn.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Bn.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Bn.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Bn.STOPPED&&(this.videoState.startTransitionTo(Bn.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(Bn.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=Ji(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 Vn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=es(this.video),a=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,a));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.firstFrame$,e.firstFrameEvent$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Yi(this.video,i.isLooped,a)),this.subscription.add(Qi(this.video,i.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),r(ys(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(Bn.PLAYING),as(i.playbackState,exports.PlaybackState.PLAYING)}),a)).add(s.pause$.subscribe((()=>{this.videoState.setState(Bn.PAUSED),as(i.playbackState,exports.PlaybackState.PAUSED)}),a)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===Bn.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===On.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Bn.READY)}))),this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var e,s,a;const r=this.player.state$.getState(),o=this.player.state$.getTransition();if(r===On.NONE||!this.videoTracks.length)return;const n=r===On.MANIFEST_LOADED&&!o,u=i.autoVideoTrackSwitching.getState(),l=i.videoTrack.getState(),d=null===(e=this.videoTracks.find((({track:{id:t}})=>t===l)))||void 0===e?void 0:e.track;i.autoVideoTrackSwitching.getTransition()&&i.autoVideoTrackSwitching.setState(u);const h=vs(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=Ss(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),forwardBufferHealth:c}),m=u?null!=p?p:d:null!=d?d:p;if(n){const e=m&&(null===(s=this.videoTracks.find((({track:t})=>t===m)))||void 0===s?void 0:s.representation);t.assertNonNullable(e);const i=Fn(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),e);t.assertNonNullable(i),this.player.initRepresentations(e.id,i.id)}else{const t=m&&(null===(a=this.videoTracks.find((({track:t})=>t===m)))||void 0===a?void 0:a.representation);if(t){const e=Fn(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(Mi.VIDEO,t.id),e&&this.player.switchRepresentation(Mi.AUDIO,e.id)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,a))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);t.assertNonNullable(e),this.videoTracks=[];for(const t of e.representations.video){const e=Mn(t);e&&this.videoTracks.push({track:e,representation:t})}this.audioRepresentations=Array.from(e.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(){Hi(this.video).then((t=>{t||(this.videoState.setState(Bn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var jn;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(jn||(jn={}));var qn=(e,i=0,s=jn.OFFSET_P)=>{switch(s){case jn.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case jn.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e};var Hn;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Hn||(Hn={}));class Gn{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new Ts(Hn.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(r)};`}),s===exports.PlaybackState.STOPPED)return void(e!==Hn.STOPPED&&(this.videoState.startTransitionTo(Hn.STOPPED),this.stop()));if(i)return;const o=null==r?void 0:r.to;if((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&e!==Hn.STOPPED)this.seek(o);else switch(s){case exports.PlaybackState.PLAYING:switch(e){case Hn.PLAYING:break;case Hn.PAUSED:case Hn.READY:this.videoState.startTransitionTo(Hn.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Hn.STOPPED:this.videoState.startTransitionTo(Hn.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Hn.PLAYING:this.videoState.startTransitionTo(Hn.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Hn.PAUSED:break;case Hn.READY:this.videoState.startTransitionTo(Hn.PAUSED),this.videoState.setState(Hn.PAUSED);break;case Hn.STOPPED:this.videoState.startTransitionTo(Hn.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((e=>{this.logRemoteEvent(e);const a=e.value;this.params.output.position$.next(a);const r=this.params.desiredState.seekPosition.getTransition();(t.isNonNullable(r)&&t.isNullable(r.to)||Math.abs(a-s)>5)&&i.next(a),s=a}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,a=this.params.output.isBuffering$.getValue(),r=s===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(Hn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Hn.PLAYING),as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.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)!==Hn.PAUSED&&t!==Hn.PLAYING||(this.videoState.setState(Hn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Hn.PLAYING&&t!==Hn.PAUSED||(this.videoState.setState(Hn.PLAYING),as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Hn.READY&&this.videoState.setState(Hn.READY)}handleRemoteStop(){this.videoState.getState()!==Hn.STOPPED&&this.videoState.setState(Hn.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),a={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};a.volume===s.volume&&a.muted==a.muted||this.params.output.volume$.next(a)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(e){var i;const s=this.params.source;let a,r,o;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const n=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:ns(t,e)?1:-1))[0];t.assertNonNullable(n);const u=i[n];t.assertNonNullable(u),a=u,r='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),a=qn(i.url),r='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return t.assertNever(e)}const n=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:a,r);n.contentUrl=a,n.streamType=o,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:l}=this.params.meta;return t.isNonNullable(u)&&(n.metadata.title=u),t.isNonNullable(l)&&(n.metadata.subtitle=l),n}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(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Promise.race([i,s]).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})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}var Yn;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Yn||(Yn={}));class Qn{constructor(e){this.subscription=new t.Subscription,this.videoState=new Ts(Yn.STOPPED),this.trackUrls={},this.textTracksManager=new Wi,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Yn.STOPPED&&(this.videoState.startTransitionTo(Yn.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(Yn.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(e===Yn.STOPPED)return this.videoState.startTransitionTo(Yn.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r||this.params.desiredState.seekPosition.startTransitionTo(t))}const o=null==r?void 0:r.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&this.seek(o),e){case Yn.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Yn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Yn.PLAYING),this.playIfAllowed()));case Yn.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Yn.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Yn.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Yn.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=Ji(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},a=es(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.firstBytes$,e.firstBytesEvent$),r(a.firstFrame$,e.firstFrameEvent$),r(a.seeked$,e.seekedEvent$),this.subscription.add(Yi(this.video,i.isLooped,s)),this.subscription.add(Qi(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Yn.PLAYING),as(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Yn.PAUSED),as(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===Yn.READY&&this.videoState.setState(Yn.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===Yn.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:a}=this.trackUrls[s];t.assertNonNullable(a,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(a=bn(a)),this.video.setAttribute('src',a),this.video.load(),this.params.output.hostname$.next(gs(a))}playIfAllowed(){Hi(this.video).then((t=>{t||(this.videoState.setState(Yn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}class zn{constructor(t,e=[],i,s,a,r){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=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let e=!1;this._xhr.onreadystatechange=()=>{var i,s,a,r,o,n,u,l;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(a=this._xhr)||void 0===a?void 0:a.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&&!e){e=!0;const t=mn(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(o=this._headersCb)||void 0===o||o.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(u=this._progressCb)||void 0===u||u.call(this,this._xhr.response))}catch(t){throw null===(l=this._errorCb)||void 0===l||l.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 Wn{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,a,r,o){this.abort((()=>{let n=0;const u=Date.now();let l=0,d=0,h=0;const c=t=>{s(Wn._str2ua(t.substr(n))),n=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=bn(p)),this._lastXhr=new zn(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(t);const e=Date.now()-u;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==a||a()}),(t=>{if(t.length-n>o&&c(t),0===d)return void(d=Date.now());h=t.length-l;const e=Date.now()-d;h>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:h,duration:e,speed:8*h/(e/1e3)}),h=0,l=t.length,d=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((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=Wn._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 Jn{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=bn(i)),new zn(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],o=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,n,u,l,d,h,c,p,m,f,b,S,v,g,y,T,E,P,k;const w=t.getElementsByTagName('SegmentBase')[0],$=w&&a(w,'indexRange').split('-'),A=w&&w.getElementsByTagName('Initialization')[0],x=A&&a(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const a=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,r=(i?i+'/':'')+(null===(d=null===(l=null===(u=null===(n=t.getElementsByTagName('BaseURL'))||void 0===n?void 0:n[0])||void 0===u?void 0:u.childNodes)||void 0===l?void 0:l[0])||void 0===d?void 0:d.data),c=null!==(h=e.getAttribute('lang'))&&void 0!==h?h:void 0;r&&o.push({id:a,url:r,language:c})}return}const N=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),_=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const R=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=R?Ln(R):void 0,r.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(b=t.attributes.getNamedItem('height'))||void 0===b?void 0:b.value),bandwidth:N,baseURL:_,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(v=null===(S=t.attributes.getNamedItem('codecs'))||void 0===S?void 0:S.value)&&void 0!==v?v:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:D,bufferSize:.1*N/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==(k=null===(P=t.attributes.getNamedItem('id'))||void 0===P?void 0:P.value)&&void 0!==k?k:void 0})})),r.length?(this._representations=r,o.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 a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let o=a.getUint32(s,!1),n=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const u=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;e+=1){const e=n+(2147483647&a.getUint32(s,!1)),i=o+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:o/r,toTime:i/r,fromOffset:n,toOffset:e-1}),n=e,o=i}const l=t.refs[t.refs.length-1];l.toTime-l.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,a;const r=()=>{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 r;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');r=e.end-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.end&&(a=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*r)))}},o=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}o()}),250)},n=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Wn({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener('sourceopen',n),i.removeEventListener('webkitsourceopen',n)};i.addEventListener('sourceopen',n,!1),i.addEventListener('webkitsourceopen',n,!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),a=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||s===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?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 a=.1;if(s.toTime<i.end+a){const e=this._findRef(s.toTime);e&&e.toTime<i.end+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((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 e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const a=i[e];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!s||a.fromTime<s.fromTime)&&(s=a)}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 Kn;!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'}(Kn||(Kn={}));const Xn=[Kn.PAUSED,Kn.PLAYING];class Zn{constructor(e){this.videoState=new Ts(Kn.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Wi,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},this.handleManifestReady=t=>{var e,i,s;const a=[];for(const r of t){const t=null!==(i=null!==(e=r.name)&&void 0!==e?e:r.id)&&void 0!==i?i:r.height.toString(10),o=null!==(s=r.name&&ss(r.name))&&void 0!==s?s:ls(r),n=r.bandwidth/1e3,u={width:r.width,height:r.height},l=r.fps;if(!o)continue;const d={id:t,quality:o,bitrate:n,size:u,fps:l};a.push({track:d,representation:r})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),this.videoState.setState(Kn.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekPositionTransition: ${JSON.stringify(r)};`}),s===exports.PlaybackState.STOPPED)return void(e!==Kn.STOPPED&&(this.videoState.startTransitionTo(Kn.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(Kn.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(i)return;const o=null==r?void 0:r.to;switch((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&Xn.includes(e)&&this.seek(o),e){case Kn.STOPPED:return this.videoState.startTransitionTo(Kn.MANIFEST_LOADED),void this.prepare();case Kn.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Kn.INITIAL_REPRESENTATION_SELECTED);case Kn.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Kn.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Kn.METADATA_LOADED:return this.videoState.startTransitionTo(Kn.READY),void this.dash.seek(null!=o?o:0);case Kn.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Kn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Kn.PLAYING),this.playIfAllowed()));case Kn.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Kn.PAUSED),this.video.pause()):(null==a?void 0:a.to)===exports.PlaybackState.PLAYING&&as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Kn.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Kn.PLAYING),this.playIfAllowed()):(null==a?void 0:a.to)===exports.PlaybackState.PAUSED&&as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Ji(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(gs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Xi(this.video),this.dash=new Jn({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},a=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},r=es(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,s));o(r.timeUpdate$,e.position$),o(r.durationChange$,e.duration$),o(r.ended$,e.endedEvent$),o(r.looped$,e.loopedEvent$),o(r.error$,e.error$),o(r.isBuffering$,e.isBuffering$),o(r.firstFrame$,e.firstFrameEvent$),this.subscription.add(r.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===Kn.PLAYING||this.videoState.getState()===Kn.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Yi(this.video,i.isLooped,s)),this.subscription.add(Qi(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,i,e),o(ys(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Kn.READY&&this.videoState.setState(Kn.READY)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Kn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Kn.PLAYING),as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Kn.METADATA_LOADED)}),s)).add(r.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(t.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i;const s=this.currentRepresentation$.getValue(),r=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),n=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),d=a();let h;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!d&&t.isNonNullable(n))h=n;else{const t=vs(this.video.buffered,1e3*this.video.currentTime),i=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);h=null===(e=Ss(r.map((({track:t})=>t)),{container:l,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:i,currentRepresentation:s}))||void 0===e?void 0:e.id}return t.isNonNullable(h)?null===(i=r.find((({track:t})=>t.id===h)))||void 0===i?void 0:i.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Kn.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Kn.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?t.height<=e.height:t===e))).subscribe((t=>{const e=vs(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!a())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(gs(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Sn(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){Hi(this.video).then((t=>{t||(this.videoState.setState(Kn.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var tu=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,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&(null==e||e())}}}),!0)},eu=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 iu=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class su{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)}async executeNextRequests(){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[a,r]=iu(s.request);if(a>=i.from&&r<=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),a=this.activeRequests.get(i.url);s&&a&&a.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(iu),s=i[0][0];let a=i[0][1];for(let t=1;t<i.length&&a<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===s?Math.max(a,s+this.params.minInitSize):Math.max(a,s+this.params.minDataSize);const r=new URL(t,location.href);r.searchParams.append('bytes',`${s}-${a}`);const o=r.toString(),n=new Cs,u=n.signal,l={url:t,from:s,to:a,loaded:0,data:null,abortController:n};u.addEventListener('abort',(()=>this.onBigRequestAbort(l)));const d=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 Os(fetch).fetch(o,{signal:u}).then((t=>{var e,i,s;if(!t.ok||!t.body)return void this.onBigRequestError(l);const[a,r]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,r);const o=a.getReader(),n=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10);l.data=new ArrayBuffer(n);const u=new Uint8Array(l.data),h=async({done:t,value:e})=>{t?this.onBigRequestProgress(l):e&&(u.set(e,l.loaded),l.loaded+=e.byteLength,this.onBigRequestProgress(l),await(null==o?void 0:o.read().then(h,su.suppressStreamErrors).catch(d)))};null==o||o.read().then(h,su.suppressStreamErrors).catch(d)}),su.suppressAbort).catch((t=>this.onBigRequestError(l,t))),l}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a}){var r,o,n,u,l,d,h;if(!this.activeRequests.has(t)||!a)return;const c=null!==(r=this.dashJsRequestQueue.get(t))&&void 0!==r?r:[];for(const r of c){const{request:c}=r,[p,m]=iu(c),f=p>=e&&m<=e+s,b=e>=p&&e+s<m,S=a.slice(p-e,Math.min(m-e+1,s));(f||b)&&(c.requestStartDate=null!==(o=c.requestStartDate)&&void 0!==o?o:new Date,c.firstByteDate=null!==(n=c.firstByteDate)&&void 0!==n?n:new Date,c.bytesLoaded=S.byteLength,c.bytesTotal=i-e),f?(c.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==r))),null===(l=r.success)||void 0===l||l.call(r,S,'',t),null===(d=this.dashMetrics)||void 0===d||d.addHttpRequest(c,t,200,{},[])):b&&(null===(h=r.progress)||void 0===h||h.call(r,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var a,r,o,n;if(null===(r=(a=this.params).onError)||void 0===r||r.call(a,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const u=null!==(o=this.dashJsRequestQueue.get(t))&&void 0!==o?o:[];for(const t of u){const[a,r]=iu(t.request);(a>=e&&a<i||r>e&&r<=i)&&(null===(n=null==t?void 0:t.error)||void 0===n||n.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,a;if(!this.activeRequests.has(t))return;const r=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of r){const[s,r]=iu(t.request);(s>=e&&s<i||r>e&&r<=i)&&(null===(a=null==t?void 0:t.abort)||void 0===a||a.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 au{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(au.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;au.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const ru=(t,e)=>{const i=new su(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new au(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var ou=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject;let a=NaN,r=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,o=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const o=e.onload,n=e.progress;e.onload=function(...e){return(e=>{var s,a,r;if(!e.getAllResponseHeaders().includes('x-playback-duration'))return;const o=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),n=parseInt(null!==(a=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==a?a:'',10),u=null!==(r=null!=n?n:1e3*o)&&void 0!==r?r:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)})(this),o(...e)},e.progress=function(...t){return this.readyState>=2&&!r&&(r=!0,s.next(Date.now()-a)),n(...t)},a=Date.now(),r=!1}return o(e)}}}),!0),{playbackDuration$:i,ping$:s}};class nu{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 uu={};var lu;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(lu||(lu={}));const du=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class hu{constructor(e){this.subscription=new t.Subscription,this.videoState=new Ts(lu.DOWNLOADING_LIB),this.textTracksManager=new Wi,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new nu,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition(),r=this.isLive$.getValue();if(this.videoState.getTransition())return;if(e===lu.DOWNLOADING_LIB||e===lu.STREAM_INITIALIZED)return;const o=null==a?void 0:a.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(o)&&e!==lu.STOPPED&&i!==exports.PlaybackState.STOPPED&&(r?this.seek(o+cu(this.liveOffset.getTotalPausedTime())):this.seek(o)),i){case exports.PlaybackState.STOPPED:switch(e){case lu.STOPPED:break;case lu.PLAYING:case lu.PAUSED:case lu.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case lu.PLAYING:break;case lu.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(cu(this.liveOffset.getTotalOffset()))):this.seek(cu(this.liveOffset.getTotalOffset()))),this.play();break;case lu.READY:this.play();break;case lu.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case lu.PLAYING:this.pause(),this.liveOffset.pause();break;case lu.PAUSED:break;case lu.READY:this.videoState.setState(lu.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case lu.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Ji(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},s=window.setTimeout((()=>e('timeout')),5e3);Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(uu.MediaPlayer=e.MediaPlayer,uu.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(uu.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(uu.Debug,'dashjs not loaded'),this.player=uu.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?Ln(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=ru(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&&eu(this.player),tu(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:bn})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(lu.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(ys(this.video),this.elementSize$),a(du(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),a(du(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const r=du(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));r.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===lu.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Gi(i.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Gi(i.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),a(du(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),a(du(this.player,'fragmentLoadingStarted').pipe(t.map((t=>gs(t.request.url)))),e.hostname$),a(du(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=ls(t),s=t.bitrate/1e3,o={width:t.width,height:t.height},n=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:o,fps:n};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===a&&(r=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&e.currentVideoTrack$.next(r),this.videoState.setState(lu.STREAM_INITIALIZED),this.videoState.startTransitionTo(lu.READY)})),a(du(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(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=Ss(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>cu(t)))),this.params.output.duration$);const o=du(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));a(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:o}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(o.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),a(du(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),a(du(this.player,'playbackEnded'),e.endedEvent$),a(du(this.player,'playbackProgress').pipe(t.map((()=>Zi(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),a(du(this.player,'playbackPlaying'),(()=>{this.videoState.setState(lu.PLAYING),as(i.playbackState,exports.PlaybackState.PLAYING)})),a(du(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(lu.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(du(this.player,'playbackPaused'),(()=>{this.videoState.setState(lu.PAUSED),as(i.playbackState,exports.PlaybackState.PAUSED)})),a(du(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===lu.READY&&this.videoState.setState(lu.READY)})),a(this.isLive$,e.isLive$),a(ys(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:n,ping$:u}=ou(this.player);a(n,this.maxSeekBackTime$),a(u.pipe(t.once()),e.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(o.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(du(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{const i=Date.now();this.subscription.add(du(this.player,'playbackPlaying').pipe(t.once()).subscribe((()=>e.firstFrameEvent$.next(Date.now()-i)),s))}),s)),this.subscription.add(Yi(this.video,i.isLooped,s));const{volumeState$:l,looped$:d}=es(this.video);this.subscription.add(Qi(this.video,i.volume,l,s)),this.subscription.add(l.subscribe(e.volume$,s)),this.subscription.add(d.subscribe(e.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(lu.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(lu.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(cu(i));const s=qn(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,jn.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(lu.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(lu.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 cu=t=>-t/1e3;function pu(){return t.now()}function mu(t){return pu()-t}function fu(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function bu(e,i,s,a){const r=window.XMLHttpRequest;let o,n,u,l,d,h=!1,c=0,p=!1,m='arraybuffer',f=7e3,b=2e3,S=()=>{if(h)return;t.assertNonNullable(l);const e=mu(l);let i;if(e<b)return i=b-e,void setTimeout(S,i);b*=2,b>f&&(b=f),n&&n.abort(),n=new r,g()};const v=()=>{if(!h){if(--c>=0)return S(),void(a&&a());h=!0,d&&d(),s&&s()}},g=()=>{l=pu(),n=new r,n.open('get',e);let s,a=0,c=0;const f=()=>(t.assertNonNullable(l),Math.max(l,Math.max(s||0,c||0)));if(o&&n.addEventListener('progress',(t=>{const e=pu();o.updateChunk&&t.loaded>a&&(o.updateChunk(f(),t.loaded-a),a=t.loaded,s=e)})),u&&(n.timeout=u,n.addEventListener('timeout',(()=>v()))),n.addEventListener('load',(()=>{if(h)return;t.assertNonNullable(n);const e=n.status;if(e>=200&&e<300){if(n.response.byteLength&&o){const t=n.response.byteLength-a;t&&o.updateChunk&&o.updateChunk(f(),t)}d&&d(),n&&i(n.response)}else v()})),n.addEventListener('error',(()=>{v()})),p){const e=()=>{t.assertNonNullable(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(c=pu(),n.removeEventListener('readystatechange',e))};n.addEventListener('readystatechange',e)}return n.responseType=m,n.send(),y},y={withBitrateReporting:t=>(o=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(c=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(b=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(d=t,y),send:g,abort:()=>{n&&(n.abort(),n=void 0),h=!0,d&&d()}};return y}class Su{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 a=e-t.start,r=t.end-t.start;i+=a;const o=t.bytes*a/r;s+=o,t.start=e,t.bytes-=o}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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 vu{constructor(t,e,i,s,a){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=a}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=pu(),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=bu(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=pu()-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=pu()}_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=pu();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 a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._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(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}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 gu{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 Su(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=fu(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}setMaxAutoQuality(t){this.maxAutoQuality=t}switchByName(t){let e;for(let i=0;i<this.manifest.length;++i)if(e=this.manifest[i],e.name===t)return void this._switchToQuality(e)}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(t){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(t):this._notifyBuffering(!0)):this.catchUp()}startPlay(t,e){this.autoQuality=e,this._initPlayerWith(t)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(t){this.manifestUrl=t,this.urlResolver=fu(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>1)}_setVideoSrc(e,i){const{logger:s,videoElement:a,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,s('setting video src'),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{t.assertNonNullable(this.mediaSource),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],i()})),this.videoPlayStarted=!1,a.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const o=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(a,'progress',(()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),r({name:'playing'})):o()}))};o()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new vu(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:a}=this.params;let r=!1,o=null,n=null,u=null,l=null,d=!1;const h=()=>{const t=r&&(!d||d===this.rep);return t||i('Not running!'),t},c=(t,e,i)=>{u&&u.abort(),u=bu(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==n||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{n=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=pu()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const a=this.bufferStates[i];t=Math.min(t,a.buf),a.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,m(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else m(1)},S=e=>{let s;const r=()=>s&&s.start?s.start.length:0,o=t=>s.start[t]/1e3,n=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,d=(t,e)=>({chunkIdx:u(t),startTS:o(t),dur:n(t),discontinuity:e}),c=()=>{let t=0;if(s&&s.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=s.dur.length-1;t>=0&&(e-=s.dur[t]/1e3,!(e<=0));--t);}return d(t,!0)},p=(t,e,i)=>{l&&l.abort(),l=bu(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{l=null})).withJSONResponse().send()};return{seek:(i,n)=>{p(e,(e=>{if(!h())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let l=0;for(let t=0;t<s.dur.length;++t)l+=s.dur[t];l>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(l/s.dur.length)),a({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=r();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(o(t)>e)return d(t);return c()}})(n))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=r(),a=t?t.chunkIdx+1:0,o=a-s.fragIndex;if(!(e<=0)){if(!t||o<0||o-e>10)return i(`Resync: offset=${o} bChunks=${e} chunk=`+JSON.stringify(t)),c();if(!(o>=e))return d(a-s.fragIndex,!1)}}}},v=()=>{r=!1,n&&n.abort(),u&&u.abort(),l&&l.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:i=>{const{videoElement:s,logger:a}=this.params;let n,u,d,m,f,g,y,T=S(e.jidxUrl),E=0;const P=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=pu(),s=Math.min(1e4,e-i);E=i;const a=()=>{l||h()&&T.seek((()=>{h()&&(E=pu(),k(),P())}))};s>0?f=window.setTimeout((()=>{this.paused?P():a()}),s):a()},k=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(d);if(i){if(d&&i.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?P():(v(),this._initPlayerWith(e)));x(i)}else P()},w=(t,e)=>{if(!h()||!this.sourceBuffer)return;let i,r,o;const n=i=>{window.setTimeout((()=>{h()&&w(t,e)}),i)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),n(100);else{const u=pu(),l=s.currentTime;!this.paused&&s.buffered.length>1&&g===l&&u-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),g!==l&&(g=l,y=u);const d=this._getBufferSizeSec();if(d>30)a(`Buffered ${d} seconds; delaying appendBuffer`),n(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:d}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;a('QuotaExceededError; delaying appendBuffer'),o=this.sourceBuffer.buffered.length,0!==o&&(i=this.sourceBuffer.buffered.start(0),r=l,r-i>4&&this.sourceBuffer.remove(i,r-3)),n(1e3)}}},$=()=>{u&&n&&(a([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(d)]),w(u,(function(){u=null,k()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{h()&&p(A(t),((e,i)=>{if(h()){if(i/=1e3,u=e,d=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{h()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},_=t=>{h()&&(e.cachedHeader=t,w(t,(()=>{n=!0,$()})))};r=!0,T.seek((e=>{h()&&(E=pu(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(d=e,k())):P())}),i),e.cachedHeader?_(e.cachedHeader):c(e.headerUrl,_,(()=>this._handleNetworkError()))},stop:v,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),t.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.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=pu();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,o=!0;const n=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(o&&t>a&&mu(r)<3e4)return;i(t)}o=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&n(),i},notifySwitch:t=>{const e=pu();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=bu(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;Hi(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 yu;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(yu||(yu={}));const Tu=[yu.PAUSED,yu.PLAYING,yu.READY],Eu=[yu.PAUSED,yu.PLAYING,yu.READY];class Pu{constructor(e){this.subscription=new t.Subscription,this.videoState=new Ts(yu.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Wi,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new nu,this._dashCb=e=>{var i,s,a,r;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,r=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),a=null!==(s=ss(e.name))&&void 0!==s?s:ls(e.video),o=e.bitrate/1e3,n={...e.video};if(!a)continue;const u={id:t,quality:a,bitrate:o,size:n};r.push({track:u,representation:e})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),(null===(a=this.videoState.getTransition())||void 0===a?void 0:a.to)===yu.MANIFEST_READY&&this.videoState.setState(yu.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(r=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===r?void 0:r.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${a}; seekPositionTransition: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED)return void(i!==yu.STOPPED&&(this.videoState.startTransitionTo(yu.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(yu.STOPPED)));if(s)return;if(Eu.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}const n=null==o?void 0:o.to;if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&Tu.includes(i))this.seek(n+ku(this.liveOffset.getTotalPausedTime()));else switch(i){case yu.STOPPED:return this.videoState.startTransitionTo(yu.MANIFEST_READY),void this.dash.attachSource(qn(this.params.source.url));case yu.MANIFEST_READY:this.videoState.startTransitionTo(yu.READY),this.prepare();break;case yu.READY:return void(a===exports.PlaybackState.PAUSED?this.videoState.setState(yu.PAUSED):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(yu.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(yu.PAUSED)}))));case yu.PLAYING:return void(a===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(yu.PAUSED),this.liveOffset.pause(),this.dash.pause()));case yu.PAUSED:return void(a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(yu.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(yu.PAUSED)})),this.params.output.position$.next(ku(this.liveOffset.getTotalOffset()))):this.seek(ku(this.liveOffset.getTotalOffset()))));default:return t.assertNever(i)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Ji(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 s=es(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===yu.READY&&this.videoState.setState(yu.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(yu.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState(yu.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map(ku)).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(Yi(this.video,this.params.desiredState.isLooped,i)).add(Qi(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(ts(this.video).subscribe(this.params.output.firstBytesEvent$)).add(Ki(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((e=>{switch(e.to){case yu.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case yu.MANIFEST_READY:case yu.READY:break;case yu.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case yu.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekPosition.stateChangeStarted$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new gu({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 e,i,s,a,r,o;const n=this.representations$.getValue(),u=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),l=null!==(a=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==a?a:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!l&&t.isNonNullable(u)?u:null===(r=Ss(n.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===r?void 0:r.id,h=null===(o=n.find((({track:t})=>t.id===d)))||void 0===o?void 0:o.representation;t.assertNonNullable(h),this.dash.startPlay(h,l),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(d),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(l)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(ku(i)),this.dash.reinit(qn(this.params.source.url,i)),this.params.output.seekedEvent$.next()}}const ku=t=>-t/1e3,wu=t=>{let e=null;if(t.QUALITY&&(e=ss(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=ls({width:i,height:s})}return null!=e?e:null},$u=async(t,e=t)=>{var i;const s=await Os(fetch).fetch(t),a=(await s.text()).split('\n'),r=[];for(let t=0;t<a.length;t++){const s=a[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const o=mn(s[1].split(',').map((t=>t.split('=')))),n=null!==(i=o.QUALITY)&&void 0!==i?i:`stream-${o.BANDWIDTH}`,u=wu(o);let l;o.BANDWIDTH&&(l=parseInt(o.BANDWIDTH,10)/1e3||void 0),!l&&o['AVERAGE-BANDWIDTH']&&(l=parseInt(o['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const d=o['FRAME-RATE']?parseFloat(o['FRAME-RATE']):void 0;let h;if(o.RESOLUTION){const[t,e]=o.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(h={width:t,height:e})}const c=new URL(a[++t],e).toString();u&&r.push({id:n,quality:u,url:c,bandwidth:l,size:h,fps:d})}return r};var Au;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Au||(Au={}));class xu{constructor(e){this.subscription=new t.Subscription,this.videoState=new Ts(Au.STOPPED),this.textTracksManager=new Wi,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Au.STOPPED&&(this.videoState.startTransitionTo(Au.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(Au.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(e===Au.STOPPED)return this.videoState.startTransitionTo(Au.READY),void this.prepare();if(a||r){const e=this.videoState.getState();this.videoState.setState(Au.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const{currentTime:i}=this.video;return this.prepare(),void(o&&!t.isNullable(o.to)||this.params.desiredState.seekPosition.startTransitionTo(i))}const n=null==o?void 0:o.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n)&&this.seek(n),e){case Au.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Au.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Au.PLAYING),this.playIfAllowed()));case Au.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Au.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Au.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Au.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Au.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Ji(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(gs(this.params.source.url)),$u(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),o=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const u=a?'master':o;return a&&!r&&s.startTransitionTo('master'),n.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},a=es(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.firstBytes$,e.firstBytesEvent$),r(a.firstFrame$,e.firstFrameEvent$),r(a.seeked$,e.seekedEvent$),this.subscription.add(Yi(this.video,i.isLooped,s)),this.subscription.add(Qi(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Au.PLAYING),as(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Au.PAUSED),as(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Au.READY&&this.videoState.setState(Au.READY),this.videoState.getState()===Au.PLAYING&&this.playIfAllowed()}),s).add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekPosition.getTransition(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(gs(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Au.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&t.isNonNullable(e.to)&&this.seek(e.to)}),s))),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){Hi(this.video).then((t=>{t||(this.videoState.setState(Au.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}var Nu;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Nu||(Nu={}));class _u{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new Ts(Nu.STOPPED),this.textTracksManager=new Wi,this.manifests$=new t.ValueSubject([]),this.liveOffset=new nu,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Nu.STOPPED&&(this.videoState.startTransitionTo(Nu.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(Nu.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const o=this.params.desiredState.seekPosition.getTransition();if(e===Nu.STOPPED)return this.videoState.startTransitionTo(Nu.READY),void this.prepare();if(a||r){const e=this.videoState.getState();this.videoState.setState(Nu.CHANGING_MANIFEST),this.videoState.startTransitionTo(e);const i=Du(this.liveOffset.getTotalOffset());return this.prepare(),void(o&&!t.isNullable(o.to)||this.params.desiredState.seekPosition.startTransitionTo(i))}const n=null==o?void 0:o.to;if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(n))return this.videoState.startTransitionTo(Nu.READY),this.seek(n+Du(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(e){case Nu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Nu.PAUSED),this.liveOffset.pause(),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Nu.PLAYING),this.playIfAllowed()));case Nu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Nu.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&as(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Nu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Nu.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(Du(this.liveOffset.getTotalOffset()))):this.seek(Du(this.liveOffset.getTotalOffset()))):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Nu.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Ji(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),$u(qn(this.params.source.url)).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(gs(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),o=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',n=this.manifests$.getValue();if(!n)return;const u=a?'master':o;return a&&!r&&s.startTransitionTo('master'),n.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},a=es(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.ended$,e.endedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.firstBytes$,e.firstBytesEvent$),r(a.firstFrame$,e.firstFrameEvent$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(Qi(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Nu.PLAYING),as(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Nu.PAUSED),as(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Nu.READY&&this.videoState.setState(Nu.READY),this.videoState.getState()===Nu.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map(Du)).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekPosition.getTransition(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(gs(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Nu.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&t.isNonNullable(e.to)&&this.seek(e.to)}),s)),this.subscription.add(a.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const o=t.merge(i.playbackState.stateChangeStarted$,i.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=qn(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',i),this.video.load(),(async t=>{const e=await Os(fetch).fetch(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0})(i).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}playIfAllowed(){Hi(this.video).then((t=>{t||(this.videoState.setState(Nu.PAUSED),this.liveOffset.pause(),as(this.params.desiredState.playbackState,exports.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(Du(i)),this.params.output.seekedEvent$.next()}}const Du=t=>-t/1e3,Ru={};var Iu;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Iu||(Iu={}));const Lu=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class Cu{constructor(e){this.subscription=new t.Subscription,this.videoState=new Ts(Iu.INITIALIZING),this.textTracksManager=new Wi,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(e===Iu.INITIALIZING)return;const r=null==a?void 0:a.to;switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&t.isNonNullable(r)&&this.seek(r),i){case exports.PlaybackState.STOPPED:switch(e){case Iu.STOPPED:break;case Iu.READY:case Iu.PLAYING:case Iu.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Iu.PLAYING:break;case Iu.STOPPED:this.prepare();break;case Iu.READY:case Iu.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Iu.PAUSED:break;case Iu.STOPPED:this.prepare();break;case Iu.READY:this.videoState.setState(Iu.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Iu.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Ji(e.container),this.params=e,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},s=window.setTimeout((()=>e('timeout')),5e3);Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(Ru.Hls=e.default,Ru.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(Ru.Hls,'hls.js not loaded'),this.hls=new Ru.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Iu.STOPPED)}subscribe(){t.assertNonNullable(Ru.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=es(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,i.position$),r(a.durationChange$,i.duration$),r(a.ended$,i.endedEvent$),r(a.looped$,i.loopedEvent$),r(a.error$,i.error$),r(a.isBuffering$,i.isBuffering$),r(a.currentBuffer$,i.currentBuffer$),r(a.firstBytes$,i.firstBytesEvent$),r(a.firstFrame$,i.firstFrameEvent$),r(a.seeked$,i.seekedEvent$),this.subscription.add(Yi(this.video,e.isLooped,s)),this.subscription.add(Qi(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lu(this.hls,Ru.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Iu.PLAYING),as(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Iu.PAUSED),as(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Iu.READY&&this.videoState.setState(Iu.READY),this.videoState.getState()===Iu.PLAYING&&this.playIfAllowed()}),s)),r(Lu(this.hls,Ru.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const a=e.name||e.height.toString(10),{width:r,height:o}=e,n=null!==(s=ss(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:ls({width:r,height:o});if(!n)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,l={id:a.toString(),quality:n,bitrate:e.bitrate/1e3,size:{width:r,height:o},fps:u};return this.trackLevels.set(a,{track:l,level:e}),t.push(l),t}),[])))),i.availableVideoTracks$),r(Lu(this.hls,Ru.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>gs(t)))),i.hostname$),this.subscription.add(Gi(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const o=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},n=Lu(this.hls,Ru.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>o(this.hls.levels[t]))));n.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(Gi(e.videoTrack,(()=>{var t;return null===(t=o(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const a=this.hls.levels.indexOf(s),r=this.hls.currentLevel,o=this.hls.levels[r];!o||s.bitrate>o.bitrate?this.hls.nextLevel=a:(this.hls.loadLevel=a,this.hls.loadLevel=a)}),{changed$:n.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(Iu.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Iu.PLAYING);await Hi(this.video)||(this.videoState.setState(Iu.PAUSED),as(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Iu.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(Iu.STOPPED),as(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}class Ou{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 Bu,Vu,Mu,Fu,Uu,ju,qu,Hu,Gu,Yu,Qu,zu,Wu,Ju,Ku,Xu,Zu;const tl=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),el=(null===(Bu=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Bu?void 0:Bu.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),il=document.createElement('video'),sl={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Mu=null===(Vu=window.SourceBuffer)||void 0===Vu?void 0:Vu.prototype)||void 0===Mu?void 0:Mu.appendBuffer)),hls:Boolean((null===(Fu=il.canPlayType)||void 0===Fu?void 0:Fu.call(il,'application/x-mpegurl'))||(null===(Uu=il.canPlayType)||void 0===Uu?void 0:Uu.call(il,'vnd.apple.mpegURL')))},al={mp4:Boolean(null===(ju=il.canPlayType)||void 0===ju?void 0:ju.call(il,'video/mp4')),webm:Boolean(null===(qu=il.canPlayType)||void 0===qu?void 0:qu.call(il,'video/webm'))},rl={h264:Boolean(null===(Gu=null===(Hu=window.MediaSource)||void 0===Hu?void 0:Hu.isTypeSupported)||void 0===Gu?void 0:Gu.call(Hu,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Qu=null===(Yu=window.MediaSource)||void 0===Yu?void 0:Yu.isTypeSupported)||void 0===Qu?void 0:Qu.call(Yu,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Wu=null===(zu=window.MediaSource)||void 0===zu?void 0:zu.isTypeSupported)||void 0===Wu?void 0:Wu.call(zu,'video/webm; codecs="vp9"')),aac:Boolean(null===(Ku=null===(Ju=window.MediaSource)||void 0===Ju?void 0:Ju.isTypeSupported)||void 0===Ku?void 0:Ku.call(Ju,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Zu=null===(Xu=window.MediaSource)||void 0===Xu?void 0:Xu.isTypeSupported)||void 0===Zu?void 0:Zu.call(Xu,'audio/webm; codecs="opus"'))},ol=(rl.h264||rl.h265)&&rl.aac,nl=!tl,ul=el||tl,ll=!sl.hls||!ul,dl=3e4,hl=18e4,cl=3,pl=100,ml={cacheDuration:12e4},fl={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},bl={maxPausedTime:3e4},Sl={maxPausedTime:3e4};class vl{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new Ou(s.filter((i=>t.isNonNullable(e.sources[i]))).filter((e=>{switch(e){case exports.VideoFormat.DASH:return sl.mse&&al.mp4&&ol&&nl;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return sl.mse&&al.mp4&&ol;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return sl.mse&&al.webm&&rl.vp9&&rl.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return sl.mse&&al.mp4&&ol;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return sl.hls&&al.mp4&&ul;case exports.VideoFormat.HLS_JS:return sl.mse&&al.mp4&&ol&&ll;case exports.VideoFormat.MPEG:return al.mp4;default:return t.assertNever(e)}}))),this.chromecastFormatsIterator=new Ou(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:'destroyProvider'});const i=this.params.desiredState.seekPosition,s=i.getTransition();s?t.isNonNullable(s.from)&&i.startTransitionTo(s.from):i.startTransitionTo(this.providerOutput.position$.getValue()),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case o.SCREEN:return this.createScreenProvider(i);case o.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:a}=this.params,r=this.providerOutput;switch(e){case exports.VideoFormat.DASH:{const o=i[e];return t.assertNonNullable(o),new Zn({container:s,source:o,desiredState:a,output:r,config:ml,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const o=i[e];return t.assertNonNullable(o),new Un({container:s,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const o=i[e];return t.assertNonNullable(o),new hu({container:s,source:o,desiredState:a,output:r,format:e,config:Sl,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const o=i[e];return t.assertNonNullable(o),new xu({container:s,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const o=i[e];return t.assertNonNullable(o),new _u({container:s,source:o,desiredState:a,output:r,config:bl,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const o=i[e];return t.assertNonNullable(o),new Cu({container:s,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const o=i[e];return t.assertNonNullable(o),new Qn({container:s,source:o,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const o=i[e];return t.assertNonNullable(o),new Pu({container:s,source:o,desiredState:a,output:r,config:fl,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:a,meta:r}=this.params,o=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(n),new Gn({connection:n,meta:r,container:s,source:i,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?o.CHROMECAST:o.SCREEN}chooseFormat(e){switch(e){case o.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case o.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case o.SCREEN:return this.screenFormatsIterator.next();case o.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case o.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case o.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var a;return s.add(t.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:dl,position$:this.providerOutput.position$,providerChanged$:this.current$},new t.Observable((e=>{const i=new t.Subscription,s=t.timeout(a.maxTransitionInterval),r=new t.ValueSubject(void 0);t.merge(a.desiredPlaybackState$.stateChangeStarted$.pipe(t.mapTo(s)),a.desiredPlaybackState$.stateChangeEnded$.pipe(t.mapTo(void 0)),a.providerChanged$.pipe(t.map((()=>r.getValue())))).subscribe(r);const o=new t.Subscription;return i.add(o),i.add(r.subscribe((t=>{o.unsubscribe(),t&&o.add(t.subscribe(e))}))),i}))).pipe(t.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(pl,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===o.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+hl?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%cl}))),s}}const gl=(t,e,i)=>i*e+(1-i)*t;class yl{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.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new fs(`raw_${s}`),this.smoothedSeries$=new fs(`smoothed_${s}`),this.reportedSeries$=new fs(`reported_${s}`)}next(e){this.slow=gl(this.slow,e,this.params.emaAlphaSlow),this.fast=gl(this.fast,e,this.params.emaAlphaFast);const i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast),this.smoothed$.next(this.smoothed),(t.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed)),this.rawSeries$.next(e),this.smoothedSeries$.next(this.smoothed)}}var Tl;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Tl||(Tl={}));const El=new Map;let Pl=Tl.RUNTIME;const kl=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(kl,'test'),localStorage.removeItem(kl),Pl=Tl.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(kl),Pl=Tl.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Pl=Tl.RUNTIME}}})();const wl=(e,i)=>{switch(Pl){case Tl.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Tl.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Tl.RUNTIME:return void El.set(e,i);default:t.assertNever(Pl)}},$l=window.navigator.connection,Al=()=>{const e=null==$l?void 0:$l.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},xl=()=>{const e=null==$l?void 0:$l.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},Nl=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class _l{constructor(e){var i,s;this.subscription=new t.Subscription,this.tuningConfig=e;const a=_l.load('one_video_throughput')||(e.useBrowserEstimation?Al():void 0)||5e3,r=null!==(s=null!==(i=_l.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?xl():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(a),this.rtt$=new t.ValueSubject(r),this.rttAdjustedThroughput$=new t.ValueSubject(Nl(a,r,e.rttPenaltyRequestSize)),this.throughput=new yl({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new yl({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=Al();e&&this.throughput.next(e);const i=xl();t.isNonNullable(i)&&this.rtt.next(i)};$l&&'onchange'in $l&&this.subscription.add(t.fromEvent($l,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{wl('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{wl('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>Nl(t,i,e.rttPenaltyRequestSize))),t.filter((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(e){let i=0,s=t.now();const a=new t.Subscription;switch(this.subscription.add(a),e.readyState){case 4:break;case 3:case 2:a.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:a.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}a.add(t.fromEvent(e,'loadend').subscribe((r=>{if(200===e.status){const e=r.loaded,a=t.now(),o=e-i,n=a-s;this.addRawSpeed(o,n)}a.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const a=t.now();let r=0,o=t.now();const n=t=>{i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=async({done:e,value:l})=>{e?this.addRawSpeed(s,t.now()-a):l&&(s+=l.byteLength,r+=l.byteLength,r>=this.tuningConfig.streamMinSampleSize&&t.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,t.now()-o),r=0,o=t.now()),await(null==i?void 0:i.read().then(u,n)))};null==i||i.read().then(u,n)}addRawSpeed(t,e){if(_l.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(e){var i;const s=(e=>{var i,s;switch(Pl){case Tl.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case Tl.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case Tl.RUNTIME:return El.get(e);default:t.assertNever(Pl)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Dl=(e=(t=>t))=>({playbackState:i,seekPosition:s,playbackAbort$:a,looped$:r,position$:o})=>new t.Observable((n=>{let u;const l=i.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),d=i.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),h=s.stateChangeEnded$.pipe(t.filter((e=>{var s,a;return t.isNonNullable(e.to)&&(null!==(a=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==a?a:i.getState())===exports.PlaybackState.PLAYING}))),c=s.stateChangeEnded$.pipe(t.filter((e=>{var s,a;return t.isNullable(e.to)&&(null!==(a=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==a?a:i.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(l,c).pipe(t.map((()=>e(o.getValue())))),m=t.merge(t.merge(d,h,a).pipe(t.map((()=>e(o.getValue())))),r.pipe(t.map(e)));return(new t.Subscription).add(p.subscribe((t=>{u=e(t)}))).add(m.subscribe((i=>{const s=e(i);if(t.isNullable(u)||u===s)return;const a={start:u,end:s};u=void 0,n.next(a)})))})),Rl=Dl((t=>t)),Il=Dl((t=>Math.round(1e3*t)+Date.now())),Ll={[o.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[o.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Ts(exports.PlaybackState.STOPPED),seekPosition:new Ts(void 0),volume:new Ts({volume:1,muted:!1}),videoTrack:new Ts(void 0),autoVideoTrackSwitching:new Ts(!0),autoVideoTrackLimits:new Ts({}),isLooped:new Ts(!1),externalTextTracks:new Ts([]),currentTextTrack:new Ts(void 0),textTrackCuesSettings:new Ts({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={started$:new t.Subject,startAttempt$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:ps},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(d)){const s=d[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:null!=a?a:s}return e})(e),this.chromecastInitializer=new h({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _l(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}>`})))),a=`Player.${String(e)}`,r=`Exception calling ${a} (${s.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:t}),t}}}})}initVideo(e){var i,s;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new vl({screenFormatsPriority:[...Ll[o.SCREEN].live,...Ll[o.SCREEN].vod],chromecastFormatsPriority:[...Ll[o.CHROMECAST].live,...Ll[o.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t){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()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({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 e;t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(i))return this.info.position$.getValue();const s=this.desiredState.seekPosition.getTransition(),a=null!==(e=null==s?void 0:s.to)&&void 0!==e?e:null==s?void 0:s.from;return t.isNonNullable(a)?a:i.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekPosition.getTransition(),i=null==e?void 0:e.to;t.isNonNullable(i)&&(this.desiredState.seekPosition.setState(i),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const e=this.desiredState.seekPosition.getTransition();t.isNonNullable(null==e?void 0:e.to)||this.desiredState.seekPosition.setState(void 0),this.events.seeked$.next()}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>ds(t)?1:ds(e)?-1:os(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekPosition:e,position$:i})=>t.merge(e.stateChangeStarted$.pipe(t.map((t=>t.to)),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>t.isNullable(e.getState())&&t.isNullable(e.getTransition()))))))({seekPosition:this.desiredState.seekPosition,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(t.map((t=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let a=0;const r=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),a=i.getValue()||s.getValue();return t&&!a})),t.filterChanged());this.subscription.add(r.subscribe((t=>{t?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const o=new t.Subscription;this.subscription.add(o);const n=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),o.unsubscribe(),e){case!0:o.add(Il({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:n,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:o.add(Rl({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:n,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=Ss(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekPosition.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekPosition',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),cs={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{hs=t})),this.providerContainer.current$.subscribe((({type:t})=>ms('provider',t))),i.duration$.subscribe((t=>ms('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>ms('tracks',t))),this.events.fatalError$.subscribe(new fs('fatalError')),this.events.managedError$.subscribe(new fs('managedError')),i.position$.subscribe(new fs('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new fs('quality')),i.currentBuffer$.subscribe(new fs('buffer')),i.isBuffering$.subscribe(new fs('isBuffering'))].forEach((t=>this.subscription.add(t))),ms('codecs',Object.keys(rl).filter((t=>rl[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.48';
6
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2018.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce'));var a,r,n,o,u,d,l;exports.PlaybackState=void 0,(a=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',a.PLAYING='playing',a.PAUSED='paused',exports.VideoFormat=void 0,(r=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',r.DASH='DASH',r.DASH_SEP='DASH_SEP',r.DASH_SEP_VK='DASH_SEP_VK',r.DASH_WEBM='DASH_WEBM',r.DASH_WEBM_VK='DASH_WEBM_VK',r.DASH_ONDEMAND='DASH_ONDEMAND',r.DASH_LIVE='DASH_LIVE',r.DASH_LIVE_WEBM='DASH_LIVE_WEBM',r.HLS='HLS',r.HLS_ONDEMAND='HLS_ONDEMAND',r.HLS_JS='HLS_JS',r.HLS_LIVE='HLS_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(n||(n={})),exports.ChromecastState=void 0,(o=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',o.AVAILABLE='AVAILABLE',o.CONNECTING='CONNECTING',o.CONNECTED='CONNECTED',exports.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(d=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',d.HTTP2='http2',d.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(l||(l={}));class h{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;var a;t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(a='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',a),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,a;null===(a=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===a||a.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,a;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(a=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===a?void 0:a.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(c),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var r;const n=a===exports.ChromecastState.CONNECTED,o=t.isNonNullable(this.connection$.getValue());if(n&&!o){const a=s.getCurrentSession();t.assertNonNullable(a);const n=a.getCastDevice(),o=null===(r=a.getMediaSession())||void 0===r?void 0:r.media.contentId;(t.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:a,castDevice:n}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.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 c=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var p;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(p||(p={}));var m,f=(e,i=0,s=p.OFFSET_P)=>{switch(s){case p.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case p.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e},S=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(m=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',m.Q_144P='144p',m.Q_240P='240p',m.Q_360P='360p',m.Q_480P='480p',m.Q_720P='720p',m.Q_1080P='1080p',m.Q_1440P='1440p',m.Q_2160P='2160p',m.Q_4320P='4320p';const b={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},v=(t,e)=>b[t].height>b[e].height,g=(t,e)=>b[t].height<b[e].height,y=Object.keys(b).sort(((t,e)=>g(t,e)?-1:1)),T=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return y.find((t=>{const e=b[t];return e.width>=s&&e.height>=i}))},E=t=>t===exports.VideoQuality.INVARIANT;class k{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var P;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={}));class w{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new k(P.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==a?void 0:a.to)===exports.PlaybackState.PAUSED||r.state!==l.Requested||e===P.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case P.PLAYING:break;case P.PAUSED:case P.READY:this.videoState.startTransitionTo(P.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case P.STOPPED:this.videoState.startTransitionTo(P.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case P.PLAYING:this.videoState.startTransitionTo(P.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case P.PAUSED:break;case P.READY:this.videoState.startTransitionTo(P.PAUSED),this.videoState.setState(P.PAUSED);break;case P.STOPPED:this.videoState.startTransitionTo(P.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(r.position)}else e!==P.STOPPED&&(this.videoState.startTransitionTo(P.STOPPED),this.stop())},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===l.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,a=this.params.output.isBuffering$.getValue(),r=s===chrome.cast.media.PlayerState.BUFFERING;switch(a!==r&&this.params.output.isBuffering$.next(r),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(P.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(P.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:l.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==P.PAUSED&&t!==P.PLAYING||(this.videoState.setState(P.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==P.PLAYING&&t!==P.PAUSED||(this.videoState.setState(P.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===P.READY&&this.videoState.setState(P.READY)}handleRemoteStop(){this.videoState.getState()!==P.STOPPED&&this.videoState.setState(P.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),a={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};a.volume===s.volume&&a.muted==a.muted||this.params.output.volume$.next(a)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(e){var i;const s=this.params.source;let a,r,n;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const o=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:g(t,e)?1:-1))[0];t.assertNonNullable(o);const u=i[o];t.assertNonNullable(u),a=u,r='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),a=f(i.url),r='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const i=s[e];t.assertNonNullable(i),a=i.url,r='application/dash+xml',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return t.assertNever(e)}const o=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:a,r);o.contentUrl=a,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return t.isNonNullable(u)&&(o.metadata.title=u),t.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===l.Applying||i.state===l.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===l.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}class ${constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class A extends ${constructor(){super(),this.listeners||$.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class x{constructor(){Object.defineProperty(this,'signal',{value:new A,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function N(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(x.prototype[Symbol.toStringTag]='AbortController',A.prototype[Symbol.toStringTag]='AbortSignal');const _=N({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),D=_?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=t;if(!N({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,n(t,e)])}return n(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,R=_?D.fetch:window.fetch;_?D.Request:window.Request;const I=_?x:window.AbortController,L=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class C{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)}async executeNextRequests(){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[a,r]=L(s.request);if(a>=i.from&&r<=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),a=this.activeRequests.get(i.url);s&&a&&a.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(L),s=i[0][0];let a=i[0][1];for(let t=1;t<i.length&&a<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===s?Math.max(a,s+this.params.minInitSize):Math.max(a,s+this.params.minDataSize);const r=new URL(t,location.href);r.searchParams.append('bytes',`${s}-${a}`);const n=r.toString(),o=new I,u=o.signal,d={url:t,from:s,to:a,loaded:0,data:null,abortController:o};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const l=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return R(n,{signal:u}).then((t=>{var e,i,s;if(!t.ok||!t.body)return void this.onBigRequestError(d);const[a,r]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,r);const n=a.getReader(),o=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10);d.data=new ArrayBuffer(o);const u=new Uint8Array(d.data),h=async({done:t,value:e})=>{t?this.onBigRequestProgress(d):e&&(u.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),await(null==n?void 0:n.read().then(h,C.suppressStreamErrors).catch(l)))};null==n||n.read().then(h,C.suppressStreamErrors).catch(l)}),C.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a}){var r,n,o,u,d,l,h;if(!this.activeRequests.has(t)||!a)return;const c=null!==(r=this.dashJsRequestQueue.get(t))&&void 0!==r?r:[];for(const r of c){const{request:c}=r,[p,m]=L(c),f=p>=e&&m<=e+s,S=e>=p&&e+s<m,b=a.slice(p-e,Math.min(m-e+1,s));(f||S)&&(c.requestStartDate=null!==(n=c.requestStartDate)&&void 0!==n?n:new Date,c.firstByteDate=null!==(o=c.firstByteDate)&&void 0!==o?o:new Date,c.bytesLoaded=b.byteLength,c.bytesTotal=i-e),f?(c.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==r))),null===(d=r.success)||void 0===d||d.call(r,b,'',t),null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(c,t,200,{},[])):S&&(null===(h=r.progress)||void 0===h||h.call(r,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var a,r,n,o;if(null===(r=(a=this.params).onError)||void 0===r||r.call(a,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const u=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of u){const[a,r]=L(t.request);(a>=e&&a<i||r>e&&r<=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,a;if(!this.activeRequests.has(t))return;const r=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of r){const[s,r]=L(t.request);(s>=e&&s<i||r>e&&r<=i)&&(null===(a=null==t?void 0:t.abort)||void 0===a||a.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 O{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(O.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;O.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const B=(t,e)=>{const i=new C(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new O(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var V=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,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&(null==e||e())}}}),!0)},M=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject;let a=NaN,r=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,n=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const n=e.onload,o=e.progress;e.onload=function(...e){return(e=>{var s,a,r;if(!e.getAllResponseHeaders().includes('x-playback-duration'))return;const n=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),o=parseInt(null!==(a=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==a?a:'',10),u=null!==(r=null!=o?o:1e3*n)&&void 0!==r?r:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)})(this),n(...e)},e.progress=function(...t){return this.readyState>=2&&!r&&(r=!0,s.next(Date.now()-a)),o(...t)},a=Date.now(),r=!1}return n(e)}}}),!0),{playbackDuration$:i,ping$:s}},F=t=>{const e=new URL(t);return e.searchParams.append('quic','1'),e.toString()},U=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 q=(e,i,s,{equal:a=((t,e)=>t===e),changed$:r,onError:n}={})=>{const o=e.getState(),u=i(),d=t.isNullable(r),l=new t.Subscription;return r&&l.add(r.subscribe((t=>{const i=e.getState();a(t,i)&&e.setState(t)}),n)),a(u,o)||(s(o),d&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),d&&e.setState(t.to)}),n)),l},j=(e,i,s)=>q(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),H=(e,i,s,a)=>q(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:s,onError:a}),G=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class Y{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const a=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(q(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(q(i.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(q(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);const a=t=>{var e,i,s,r,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!==(r=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==r?r:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',a))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',a)}))),this.subscription.add(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(Y.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&G(i,e)?i.mode='showing':i.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var Q=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class z{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}var W=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadeddata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());class J{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:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var K=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{start:s,end:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{start:s,end:a}},X=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadedmetadata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());const Z=e=>{const i=(i,s=(()=>{}))=>t.fromEvent(e,i).pipe(t.map(s)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((()=>e.readyState<3)),t.filterChanged()),a=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>K(e.buffered,e.currentTime)))),r=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'error').pipe(t.map((()=>{const t=e.error;return{id:t?`MediaError#${t.code}`:'HtmlVideoError',message:t?t.message:'Error event from HTML video element'}}))),o=i('timeupdate',(()=>e.currentTime)),u=new t.Subject;let d;return o.subscribe((i=>{e.loop&&t.isNonNullable(d)&&t.isNonNullable(i)&&d>=e.duration-.3&&i<=.3&&u.next(d),d=i})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:u,error$:n,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:o,durationChange$:i('durationchange',(()=>e.duration)),isBuffering$:s,currentBuffer$:a,volumeState$:r,firstBytes$:X(e),firstFrame$:W(e)}},tt=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var et='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},it=function(t){return t&&t.Math==Math&&t},st=it('object'==typeof globalThis&&globalThis)||it('object'==typeof window&&window)||it('object'==typeof self&&self)||it('object'==typeof et&&et)||function(){return this}()||Function('return this')(),at=function(t){try{return!!t()}catch(t){return!0}},rt=!at((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),nt=rt,ot=Function.prototype,ut=ot.apply,dt=ot.call,lt='object'==typeof Reflect&&Reflect.apply||(nt?dt.bind(ut):function(){return dt.apply(ut,arguments)}),ht=rt,ct=Function.prototype,pt=ct.bind,mt=ct.call,ft=ht&&pt.bind(mt,mt),St=ht?function(t){return t&&ft(t)}:function(t){return t&&function(){return mt.apply(t,arguments)}},bt=function(t){return'function'==typeof t},vt={},gt=!at((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),yt=rt,Tt=Function.prototype.call,Et=yt?Tt.bind(Tt):function(){return Tt.apply(Tt,arguments)},kt={},Pt={}.propertyIsEnumerable,wt=Object.getOwnPropertyDescriptor,$t=wt&&!Pt.call({1:2},1);kt.f=$t?function(t){var e=wt(this,t);return!!e&&e.enumerable}:Pt;var At,xt,Nt=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},_t=St,Dt=_t({}.toString),Rt=_t(''.slice),It=function(t){return Rt(Dt(t),8,-1)},Lt=St,Ct=at,Ot=It,Bt=st.Object,Vt=Lt(''.split),Mt=Ct((function(){return!Bt('z').propertyIsEnumerable(0)}))?function(t){return'String'==Ot(t)?Vt(t,''):Bt(t)}:Bt,Ft=st.TypeError,Ut=function(t){if(null==t)throw Ft('Can\'t call method on '+t);return t},qt=Mt,jt=Ut,Ht=function(t){return qt(jt(t))},Gt=bt,Yt=function(t){return'object'==typeof t?null!==t:Gt(t)},Qt={},zt=Qt,Wt=st,Jt=bt,Kt=function(t){return Jt(t)?t:void 0},Xt=function(t,e){return arguments.length<2?Kt(zt[t])||Kt(Wt[t]):zt[t]&&zt[t][e]||Wt[t]&&Wt[t][e]},Zt=St({}.isPrototypeOf),te=st,ee=Xt('navigator','userAgent')||'',ie=te.process,se=te.Deno,ae=ie&&ie.versions||se&&se.version,re=ae&&ae.v8;re&&(xt=(At=re.split('.'))[0]>0&&At[0]<4?1:+(At[0]+At[1])),!xt&&ee&&(!(At=ee.match(/Edge\/(\d+)/))||At[1]>=74)&&(At=ee.match(/Chrome\/(\d+)/))&&(xt=+At[1]);var ne=xt,oe=at,ue=!!Object.getOwnPropertySymbols&&!oe((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),de=ue&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,le=Xt,he=bt,ce=Zt,pe=de,me=st.Object,fe=pe?function(t){return'symbol'==typeof t}:function(t){var e=le('Symbol');return he(e)&&ce(e.prototype,me(t))},Se=st.String,be=function(t){try{return Se(t)}catch(t){return'Object'}},ve=bt,ge=be,ye=st.TypeError,Te=function(t){if(ve(t))return t;throw ye(ge(t)+' is not a function')},Ee=Te,ke=function(t,e){var i=t[e];return null==i?void 0:Ee(i)},Pe=Et,we=bt,$e=Yt,Ae=st.TypeError,xe={exports:{}},Ne=st,_e=Object.defineProperty,De=function(t,e){try{_e(Ne,t,{value:e,configurable:!0,writable:!0})}catch(i){Ne[t]=e}return e},Re=st['__core-js_shared__']||De('__core-js_shared__',{}),Ie=Re;(xe.exports=function(t,e){return Ie[t]||(Ie[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 Le=Ut,Ce=st.Object,Oe=function(t){return Ce(Le(t))},Be=Oe,Ve=St({}.hasOwnProperty),Me=Object.hasOwn||function(t,e){return Ve(Be(t),e)},Fe=St,Ue=0,qe=Math.random(),je=Fe(1..toString),He=function(t){return'Symbol('+(void 0===t?'':t)+')_'+je(++Ue+qe,36)},Ge=st,Ye=xe.exports,Qe=Me,ze=He,We=ue,Je=de,Ke=Ye('wks'),Xe=Ge.Symbol,Ze=Xe&&Xe.for,ti=Je?Xe:Xe&&Xe.withoutSetter||ze,ei=function(t){if(!Qe(Ke,t)||!We&&'string'!=typeof Ke[t]){var e='Symbol.'+t;We&&Qe(Xe,t)?Ke[t]=Xe[t]:Ke[t]=Je&&Ze?Ze(e):ti(e)}return Ke[t]},ii=Et,si=Yt,ai=fe,ri=ke,ni=function(t,e){var i,s;if('string'===e&&we(i=t.toString)&&!$e(s=Pe(i,t)))return s;if(we(i=t.valueOf)&&!$e(s=Pe(i,t)))return s;if('string'!==e&&we(i=t.toString)&&!$e(s=Pe(i,t)))return s;throw Ae('Can\'t convert object to primitive value')},oi=ei,ui=st.TypeError,di=oi('toPrimitive'),li=function(t,e){if(!si(t)||ai(t))return t;var i,s=ri(t,di);if(s){if(void 0===e&&(e='default'),i=ii(s,t,e),!si(i)||ai(i))return i;throw ui('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),ni(t,e)},hi=fe,ci=function(t){var e=li(t,'string');return hi(e)?e:e+''},pi=Yt,mi=st.document,fi=pi(mi)&&pi(mi.createElement),Si=function(t){return fi?mi.createElement(t):{}},bi=Si,vi=!gt&&!at((function(){return 7!=Object.defineProperty(bi('div'),'a',{get:function(){return 7}}).a})),gi=gt,yi=Et,Ti=kt,Ei=Nt,ki=Ht,Pi=ci,wi=Me,$i=vi,Ai=Object.getOwnPropertyDescriptor;vt.f=gi?Ai:function(t,e){if(t=ki(t),e=Pi(e),$i)try{return Ai(t,e)}catch(t){}if(wi(t,e))return Ei(!yi(Ti.f,t,e),t[e])};var xi=at,Ni=bt,_i=/#|\.prototype\./,Di=function(t,e){var i=Ii[Ri(t)];return i==Ci||i!=Li&&(Ni(e)?xi(e):!!e)},Ri=Di.normalize=function(t){return String(t).replace(_i,'.').toLowerCase()},Ii=Di.data={},Li=Di.NATIVE='N',Ci=Di.POLYFILL='P',Oi=Di,Bi=Te,Vi=rt,Mi=St(St.bind),Fi=function(t,e){return Bi(t),void 0===e?t:Vi?Mi(t,e):function(){return t.apply(e,arguments)}},Ui={},qi=gt&&at((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ji=st,Hi=Yt,Gi=ji.String,Yi=ji.TypeError,Qi=function(t){if(Hi(t))return t;throw Yi(Gi(t)+' is not an object')},zi=gt,Wi=vi,Ji=qi,Ki=Qi,Xi=ci,Zi=st.TypeError,ts=Object.defineProperty,es=Object.getOwnPropertyDescriptor;Ui.f=zi?Ji?function(t,e,i){if(Ki(t),e=Xi(e),Ki(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=es(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 ts(t,e,i)}:ts:function(t,e,i){if(Ki(t),e=Xi(e),Ki(i),Wi)try{return ts(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Zi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var is=Ui,ss=Nt,as=gt?function(t,e,i){return is.f(t,e,ss(1,i))}:function(t,e,i){return t[e]=i,t},rs=st,ns=lt,os=St,us=bt,ds=vt.f,ls=Oi,hs=Qt,cs=Fi,ps=as,ms=Me,fs=function(t){var e=function(i,s,a){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,a)}return ns(t,this,arguments)};return e.prototype=t.prototype,e},Ss=function(t,e){var i,s,a,r,n,o,u,d,l=t.target,h=t.global,c=t.stat,p=t.proto,m=h?rs:c?rs[l]:(rs[l]||{}).prototype,f=h?hs:hs[l]||ps(hs,l,{})[l],S=f.prototype;for(a in e)i=!ls(h?a:l+(c?'.':'#')+a,t.forced)&&m&&ms(m,a),n=f[a],i&&(o=t.noTargetGet?(d=ds(m,a))&&d.value:m[a]),r=i&&o?o:e[a],i&&typeof n==typeof r||(u=t.bind&&i?cs(r,rs):t.wrap&&i?fs(r):p&&us(r)?os(r):r,(t.sham||r&&r.sham||n&&n.sham)&&ps(u,'sham',!0),ps(f,a,u),p&&(ms(hs,s=l+'Prototype')||ps(hs,s,{}),ps(hs[s],a,r),t.real&&S&&!S[a]&&ps(S,a,r)))},bs=Math.ceil,vs=Math.floor,gs=function(t){var e=+t;return e!=e||0===e?0:(e>0?vs:bs)(e)},ys=gs,Ts=Math.min,Es=function(t){return t>0?Ts(ys(t),9007199254740991):0},ks=function(t){return Es(t.length)},Ps=Oe,ws=ks,$s=gs;Ss({target:'Array',proto:!0},{at:function(t){var e=Ps(this),i=ws(e),s=$s(t),a=s>=0?s:i+s;return a<0||a>=i?void 0:e[a]}});var As=Xt('Array','at');let xs=!1,Ns={};const _s=t=>{t(Ns)},Ds=(t,e)=>{var i;xs&&(Ns.meta=null!==(i=Ns.meta)&&void 0!==i?i:{},Ns.meta[t]=e)};class Rs{constructor(t){this.name=t}next(t){var e,i;if(!xs)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 Is=new Rs('best_bitrate'),Ls=(e,{container:i,throughput:s,tuning:a,limits:r,forwardBufferHealth:n,currentRepresentation:o})=>{var u,d,l,h;const c=a.usePixelRatio&&null!==(u=window.devicePixelRatio)&&void 0!==u?u:1,p=a.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*c*a.containerSizeFactor,height:i.height*c*a.containerSizeFactor},m=p&&T(p),f=e.filter((t=>!E(t.quality))).sort(((t,e)=>v(t.quality,e.quality)?-1:1)),S=null===(d=As(f,-1))||void 0===d?void 0:d.quality,y=null===(l=As(f,0))||void 0===l?void 0:l.quality,k=t.isNullable(r)||t.isNonNullable(r.min)&&t.isNonNullable(r.max)&&g(r.max,r.min)||t.isNonNullable(r.min)&&y&&v(r.min,y)||t.isNonNullable(r.max)&&S&&g(r.max,S),P=f.filter((e=>{var i;const u=!m||g(e.quality,m),d=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s>=e.bitrate*(l=null!=n?n:.5,h=a.bitrateFactorAtEmptyBuffer,c=a.bitrateFactorAtFullBuffer,(h-c)*Math.pow(2,-10*l)+c);var l,h,c;const p=!a.lazyQualitySwitch||!o||(null!=n?n:.5)>=.5||((null===(i=e.size)||void 0===i?void 0:i.height)||0)<=((null==o?void 0:o.height)||0),f=k||(t.isNullable(r.max)||(S=e.quality,v=r.max,b[S].height<=b[v].height))&&(t.isNullable(r.min)||((t,e)=>b[t].height>=b[e].height)(e.quality,r.min));var S,v;return u&&d&&p&&f}))[0];return P&&P.bitrate&&Is.next(P.bitrate),null!==(h=null!=P?P:f[Math.ceil((f.length-1)/2)])&&void 0!==h?h:e[0]};var Cs=t=>new URL(t).hostname;const Os=(e,i=300)=>new t.Observable((a=>{const{width:r,height:n}=e.getBoundingClientRect();if(a.next({width:r,height:n}),!window.ResizeObserver)return;const o=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,r;i.contentBoxSize&&i.contentBoxSize[0]?(r=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,r=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(r)&&a.next({width:s,height:r})}),i));return o.observe(e),()=>o.disconnect()})),Bs={};var Vs;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Vs||(Vs={}));const Ms=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class Fs{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(Vs.DOWNLOADING_LIB),this.textTracksManager=new Y,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new z,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==Vs.DOWNLOADING_LIB&&e!==Vs.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&e!==Vs.STOPPED&&i!==exports.PlaybackState.STOPPED&&(r?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case exports.PlaybackState.STOPPED:switch(e){case Vs.STOPPED:break;case Vs.PLAYING:case Vs.PAUSED:case Vs.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Vs.PLAYING:break;case Vs.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Vs.READY:this.play();break;case Vs.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Vs.PLAYING:this.pause(),this.liveOffset.pause();break;case Vs.PAUSED:break;case Vs.READY:this.videoState.setState(Vs.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Vs.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Cs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(Bs.MediaPlayer=e.MediaPlayer,Bs.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(Bs.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(Bs.Debug,'dashjs not loaded'),this.player=Bs.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?tt(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=B(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&&U(this.player),V(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:F})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Vs.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(Os(this.video),this.elementSize$),a(Ms(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),a(Ms(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const r=Ms(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));r.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===Vs.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(q(i.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:r.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(q(i.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),a(Ms(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),a(Ms(this.player,'fragmentLoadingStarted').pipe(t.map((t=>Cs(t.request.url)))),e.hostname$),a(Ms(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=T(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===a&&(r=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&e.currentVideoTrack$.next(r),this.videoState.setState(Vs.STREAM_INITIALIZED),this.videoState.startTransitionTo(Vs.READY)})),a(Ms(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(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=Ls(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const n=Ms(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));a(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:n}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(n.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),a(Ms(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),a(Ms(this.player,'playbackEnded'),e.endedEvent$),a(Ms(this.player,'playbackProgress').pipe(t.map((()=>K(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),a(Ms(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Vs.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)})),a(Ms(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Vs.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Ms(this.player,'playbackPaused'),(()=>{this.videoState.setState(Vs.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)})),a(Ms(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Vs.READY&&this.videoState.setState(Vs.READY)})),a(this.isLive$,e.isLive$),a(Os(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:o,ping$:u}=M(this.player);a(o,this.maxSeekBackTime$),a(u.pipe(t.once()),e.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(n.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(Ms(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{const i=Date.now();this.subscription.add(Ms(this.player,'playbackPlaying').pipe(t.once()).subscribe((()=>e.firstFrameEvent$.next(Date.now()-i)),s))}),s)),this.subscription.add(j(this.video,i.isLooped,s));const{volumeState$:d,looped$:l}=Z(this.video);this.subscription.add(H(this.video,i.volume,d,s)),this.subscription.add(d.subscribe(e.volume$,s)),this.subscription.add(l.subscribe(e.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Vs.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Vs.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=f(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,p.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Vs.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Vs.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var Us=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},qs=async t=>{const e=t.muted;try{await 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{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function js(){return t.now()}function Hs(t){return js()-t}function Gs(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function Ys(e,i,s,a){const r=window.XMLHttpRequest;let n,o,u,d,l,h=!1,c=0,p=!1,m='arraybuffer',f=7e3,S=2e3,b=()=>{if(h)return;t.assertNonNullable(d);const e=Hs(d);let i;if(e<S)return i=S-e,void setTimeout(b,i);S*=2,S>f&&(S=f),o&&o.abort(),o=new r,g()};const v=()=>{if(!h){if(--c>=0)return b(),void(a&&a());h=!0,l&&l(),s&&s()}},g=()=>{d=js(),o=new r,o.open('get',e);let s,a=0,c=0;const f=()=>(t.assertNonNullable(d),Math.max(d,Math.max(s||0,c||0)));if(n&&o.addEventListener('progress',(t=>{const e=js();n.updateChunk&&t.loaded>a&&(n.updateChunk(f(),t.loaded-a),a=t.loaded,s=e)})),u&&(o.timeout=u,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(h)return;t.assertNonNullable(o);const e=o.status;if(e>=200&&e<300){if(o.response.byteLength&&n){const t=o.response.byteLength-a;t&&n.updateChunk&&n.updateChunk(f(),t)}l&&l(),o&&i(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),p){const e=()=>{t.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(c=js(),o.removeEventListener('readystatechange',e))};o.addEventListener('readystatechange',e)}return o.responseType=m,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(c=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(S=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(l=t,y),send:g,abort:()=>{o&&(o.abort(),o=void 0),h=!0,l&&l()}};return y}class Qs{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 a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/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 zs{constructor(t,e,i,s,a){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=a}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=js(),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=Ys(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=js()-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=js()}_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=js();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 a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._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(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}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 Ws{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 Qs(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Gs(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=Gs(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,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zs(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:a}=this.params;let r=!1,n=null,o=null,u=null,d=null,l=!1;const h=()=>{const t=r&&(!l||l===this.rep);return t||i('Not running!'),t},c=(t,e,i)=>{u&&u.abort(),u=Ys(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==o||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{o=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=js()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const a=this.bufferStates[i];t=Math.min(t,a.buf),a.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,m(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else m(1)},b=e=>{let s;const r=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,l=(t,e)=>({chunkIdx:u(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(s&&s.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=s.dur.length-1;t>=0&&(e-=s.dur[t]/1e3,!(e<=0));--t);}return l(t,!0)},p=(t,e,i)=>{d&&d.abort(),d=Ys(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{d=null})).withJSONResponse().send()};return{seek:(i,o)=>{p(e,(e=>{if(!h())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let d=0;for(let t=0;t<s.dur.length;++t)d+=s.dur[t];d>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(d/s.dur.length)),a({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=r();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(n(t)>e)return l(t);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=r(),a=t?t.chunkIdx+1:0,n=a-s.fragIndex;if(!(e<=0)){if(!t||n<0||n-e>10)return i(`Resync: offset=${n} bChunks=${e} chunk=`+JSON.stringify(t)),c();if(!(n>=e))return l(a-s.fragIndex,!1)}}}},v=()=>{r=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:i=>{const{videoElement:s,logger:a}=this.params;let o,u,l,m,f,g,y,T=b(e.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=js(),s=Math.min(1e4,e-i);E=i;const a=()=>{d||h()&&T.seek((()=>{h()&&(E=js(),P(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():a()}),s):a()},P=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(l);if(i){if(l&&i.discontinuity)return a('Detected discontinuity; restarting playback'),void(this.paused?k():(v(),this._initPlayerWith(e)));x(i)}else k()},w=(t,e)=>{if(!h()||!this.sourceBuffer)return;let i,r,n;const o=i=>{window.setTimeout((()=>{h()&&w(t,e)}),i)};if(this.sourceBuffer.updating)a('Source buffer is updating; delaying appendBuffer'),o(100);else{const u=js(),d=s.currentTime;!this.paused&&s.buffered.length>1&&g===d&&u-y>500&&(a('Stall suspected; trying to fix'),this._fixupStall()),g!==d&&(g=d,y=u);const l=this._getBufferSizeSec();if(l>30)a(`Buffered ${l} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:l}),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;a('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(i=this.sourceBuffer.buffered.start(0),r=d,r-i>4&&this.sourceBuffer.remove(i,r-3)),o(1e3)}}},$=()=>{u&&o&&(a([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(l)]),w(u,(function(){u=null,P()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{h()&&p(A(t),((e,i)=>{if(h()){if(i/=1e3,u=e,l=t,n=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{h()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},_=t=>{h()&&(e.cachedHeader=t,w(t,(()=>{o=!0,$()})))};r=!0,T.seek((e=>{h()&&(E=js(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(l=e,P())):k())}),i),e.cachedHeader?_(e.cachedHeader):c(e.headerUrl,_,(()=>this._handleNetworkError()))},stop:v,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),t.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.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=js();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Hs(r)<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=js();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=Ys(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;qs(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 Js;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Js||(Js={}));const Ks=[Js.PAUSED,Js.PLAYING,Js.READY],Xs=[Js.PAUSED,Js.PLAYING,Js.READY];class Zs{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(Js.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new Y,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new z,this._dashCb=e=>{var i,s,a,r;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,r=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),a=null!==(s=Us(e.name))&&void 0!==s?s:T(e.video),n=e.bitrate/1e3,o={...e.video};if(!a)continue;const u={id:t,quality:a,bitrate:n,size:o};r.push({track:u,representation:e})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),(null===(a=this.videoState.getTransition())||void 0===a?void 0:a.to)===Js.MANIFEST_READY&&this.videoState.setState(Js.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(r=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===r?void 0:r.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(n)};`}),a!==exports.PlaybackState.STOPPED){if(!s){if(Xs.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&Ks.includes(i))this.seek(n.position-this.liveOffset.getTotalPausedTime());else switch(i){case Js.STOPPED:return this.videoState.startTransitionTo(Js.MANIFEST_READY),void this.dash.attachSource(f(this.params.source.url));case Js.MANIFEST_READY:this.videoState.startTransitionTo(Js.READY),this.prepare();break;case Js.READY:return void(a===exports.PlaybackState.PAUSED?this.videoState.setState(Js.PAUSED):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Js.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Js.PAUSED)}))));case Js.PLAYING:return void(a===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(Js.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Js.PAUSED:return void(a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Js.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(Js.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==Js.STOPPED&&(this.videoState.startTransitionTo(Js.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Js.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Q(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(Cs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Z(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Js.READY&&this.videoState.setState(Js.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(Js.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===l.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Js.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(j(this.video,this.params.desiredState.isLooped,i)).add(H(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(X(this.video).subscribe(this.params.output.firstBytesEvent$)).add(W(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&b[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case Js.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case Js.MANIFEST_READY:case Js.READY:break;case Js.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case Js.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Ws({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 e,i,s,a,r,n;const o=this.representations$.getValue(),u=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),d=null!==(a=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==a?a:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&t.isNonNullable(u)?u:null===(r=Ls(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===r?void 0:r.id,h=null===(n=o.find((({track:t})=>t.id===l)))||void 0===n?void 0:n.representation;t.assertNonNullable(h,'Representations missing'),this.dash.startPlay(h,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(f(this.params.source.url,i))}}var ta=t=>{var e,i;const s=t.get('X-Delivery-Type'),a=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===a?void 0:null!==(i={1:!0,0:!1}[a])&&void 0!==i?i:void 0}},ea=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};var ia={},sa=bt,aa=Re,ra=St(Function.toString);sa(aa.inspectSource)||(aa.inspectSource=function(t){return ra(t)});var na,oa,ua,da=bt,la=aa.inspectSource,ha=st.WeakMap,ca=da(ha)&&/native code/.test(la(ha)),pa=xe.exports,ma=He,fa=pa('keys'),Sa=function(t){return fa[t]||(fa[t]=ma(t))},ba={},va=ca,ga=st,ya=St,Ta=Yt,Ea=as,ka=Me,Pa=Re,wa=Sa,$a=ba,Aa=ga.TypeError,xa=ga.WeakMap;if(va||Pa.state){var Na=Pa.state||(Pa.state=new xa),_a=ya(Na.get),Da=ya(Na.has),Ra=ya(Na.set);na=function(t,e){if(Da(Na,t))throw new Aa('Object already initialized');return e.facade=t,Ra(Na,t,e),e},oa=function(t){return _a(Na,t)||{}},ua=function(t){return Da(Na,t)}}else{var Ia=wa('state');$a[Ia]=!0,na=function(t,e){if(ka(t,Ia))throw new Aa('Object already initialized');return e.facade=t,Ea(t,Ia,e),e},oa=function(t){return ka(t,Ia)?t[Ia]:{}},ua=function(t){return ka(t,Ia)}}var La={set:na,get:oa,has:ua,enforce:function(t){return ua(t)?oa(t):na(t,{})},getterFor:function(t){return function(e){var i;if(!Ta(e)||(i=oa(e)).type!==t)throw Aa('Incompatible receiver, '+t+' required');return i}}},Ca=gt,Oa=Me,Ba=Function.prototype,Va=Ca&&Object.getOwnPropertyDescriptor,Ma=Oa(Ba,'name'),Fa={EXISTS:Ma,PROPER:Ma&&'something'===function(){}.name,CONFIGURABLE:Ma&&(!Ca||Ca&&Va(Ba,'name').configurable)},Ua={},qa=gs,ja=Math.max,Ha=Math.min,Ga=Ht,Ya=function(t,e){var i=qa(t);return i<0?ja(i+e,0):Ha(i,e)},Qa=ks,za=function(t){return function(e,i,s){var a,r=Ga(e),n=Qa(r),o=Ya(s,n);if(t&&i!=i){for(;n>o;)if((a=r[o++])!=a)return!0}else for(;n>o;o++)if((t||o in r)&&r[o]===i)return t||o||0;return!t&&-1}},Wa={includes:za(!0),indexOf:za(!1)},Ja=Me,Ka=Ht,Xa=Wa.indexOf,Za=ba,tr=St([].push),er=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],ir=function(t,e){var i,s=Ka(t),a=0,r=[];for(i in s)!Ja(Za,i)&&Ja(s,i)&&tr(r,i);for(;e.length>a;)Ja(s,i=e[a++])&&(~Xa(r,i)||tr(r,i));return r},sr=er,ar=Object.keys||function(t){return ir(t,sr)},rr=gt,nr=qi,or=Ui,ur=Qi,dr=Ht,lr=ar;Ua.f=rr&&!nr?Object.defineProperties:function(t,e){ur(t);for(var i,s=dr(e),a=lr(e),r=a.length,n=0;r>n;)or.f(t,i=a[n++],s[i]);return t};var hr,cr=Xt('document','documentElement'),pr=Qi,mr=Ua,fr=er,Sr=ba,br=cr,vr=Si,gr=Sa('IE_PROTO'),yr=function(){},Tr=function(t){return'<script>'+t+'<\/script>'},Er=function(t){t.write(Tr('')),t.close();var e=t.parentWindow.Object;return t=null,e},kr=function(){try{hr=new ActiveXObject('htmlfile')}catch(t){}var t,e;kr='undefined'!=typeof document?document.domain&&hr?Er(hr):((e=vr('iframe')).style.display='none',br.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Tr('document.F=Object')),t.close(),t.F):Er(hr);for(var i=fr.length;i--;)delete kr.prototype[fr[i]];return kr()};Sr[gr]=!0;var Pr,wr,$r,Ar=Object.create||function(t,e){var i;return null!==t?(yr.prototype=pr(t),i=new yr,yr.prototype=null,i[gr]=t):i=kr(),void 0===e?i:mr.f(i,e)},xr=!at((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Nr=st,_r=Me,Dr=bt,Rr=Oe,Ir=xr,Lr=Sa('IE_PROTO'),Cr=Nr.Object,Or=Cr.prototype,Br=Ir?Cr.getPrototypeOf:function(t){var e=Rr(t);if(_r(e,Lr))return e[Lr];var i=e.constructor;return Dr(i)&&e instanceof i?i.prototype:e instanceof Cr?Or:null},Vr=as,Mr=function(t,e,i,s){s&&s.enumerable?t[e]=i:Vr(t,e,i)},Fr=at,Ur=bt,qr=Ar,jr=Br,Hr=Mr,Gr=ei('iterator'),Yr=!1;[].keys&&('next'in($r=[].keys())?(wr=jr(jr($r)))!==Object.prototype&&(Pr=wr):Yr=!0);var Qr=null==Pr||Fr((function(){var t={};return Pr[Gr].call(t)!==t}));Ur((Pr=Qr?{}:qr(Pr))[Gr])||Hr(Pr,Gr,(function(){return this}));var zr={IteratorPrototype:Pr,BUGGY_SAFARI_ITERATORS:Yr},Wr={};Wr[ei('toStringTag')]='z';var Jr='[object z]'===String(Wr),Kr=st,Xr=Jr,Zr=bt,tn=It,en=ei('toStringTag'),sn=Kr.Object,an='Arguments'==tn(function(){return arguments}()),rn=Xr?tn: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=sn(t),en))?i:an?tn(e):'Object'==(s=tn(e))&&Zr(e.callee)?'Arguments':s},nn=rn,on=Jr?{}.toString:function(){return'[object '+nn(this)+']'},un=Jr,dn=Ui.f,ln=as,hn=Me,cn=on,pn=ei('toStringTag'),mn=function(t,e,i,s){if(t){var a=i?t:t.prototype;hn(a,pn)||dn(a,pn,{configurable:!0,value:e}),s&&!un&&ln(a,'toString',cn)}},fn=zr.IteratorPrototype,Sn=Ar,bn=Nt,vn=mn,gn=ia,yn=function(){return this},Tn=st,En=(Tn.String,Tn.TypeError,St);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=En(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var kn=Ss,Pn=Et,wn=function(t,e,i,s){var a=e+' Iterator';return t.prototype=Sn(fn,{next:bn(+!s,i)}),vn(t,a,!1,!0),gn[a]=yn,t},$n=Br,An=mn,xn=Mr,Nn=ia,_n=Fa.PROPER,Dn=zr.BUGGY_SAFARI_ITERATORS,Rn=ei('iterator'),In=function(){return this},Ln=Ht,Cn=ia,On=La;Ui.f;var Bn=function(t,e,i,s,a,r,n){wn(i,e,s);var o,u,d,l=function(t){if(t===a&&f)return f;if(!Dn&&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)}},h=e+' Iterator',c=!1,p=t.prototype,m=p[Rn]||p['@@iterator']||a&&p[a],f=!Dn&&m||l(a),S='Array'==e&&p.entries||m;if(S&&(o=$n(S.call(new t)))!==Object.prototype&&o.next&&(An(o,h,!0,!0),Nn[h]=In),_n&&'values'==a&&m&&'values'!==m.name&&(c=!0,f=function(){return Pn(m,this)}),a)if(u={values:l('values'),keys:r?f:l('keys'),entries:l('entries')},n)for(d in u)(Dn||c||!(d in p))&&xn(p,d,u[d]);else kn({target:e,proto:!0,forced:Dn||c},u);return n&&p[Rn]!==f&&xn(p,Rn,f,{name:a}),Nn[e]=f,u},Vn=On.set,Mn=On.getterFor('Array Iterator');Bn(Array,'Array',(function(t,e){Vn(this,{type:'Array Iterator',target:Ln(t),index:0,kind:e})}),(function(){var t=Mn(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'),Cn.Arguments=Cn.Array;var Fn=ia,Un=ei('iterator'),qn=Array.prototype,jn=rn,Hn=ke,Gn=ia,Yn=ei('iterator'),Qn=function(t){if(null!=t)return Hn(t,Yn)||Hn(t,'@@iterator')||Gn[jn(t)]},zn=Et,Wn=Te,Jn=Qi,Kn=be,Xn=Qn,Zn=st.TypeError,to=Et,eo=Qi,io=ke,so=Fi,ao=Et,ro=Qi,no=be,oo=function(t){return void 0!==t&&(Fn.Array===t||qn[Un]===t)},uo=ks,lo=Zt,ho=function(t,e){var i=arguments.length<2?Xn(t):e;if(Wn(i))return Jn(zn(i,t));throw Zn(Kn(t)+' is not iterable')},co=Qn,po=function(t,e,i){var s,a;eo(t);try{if(!(s=io(t,'return'))){if('throw'===e)throw i;return i}s=to(s,t)}catch(t){a=!0,s=t}if('throw'===e)throw i;if(a)throw s;return eo(s),i},mo=st.TypeError,fo=function(t,e){this.stopped=t,this.result=e},So=fo.prototype,bo=ci,vo=Ui,go=Nt,yo=function(t,e,i){var s,a,r,n,o,u,d,l=i&&i.that,h=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=so(e,l),f=function(t){return s&&po(s,'normal',t),new fo(!0,t)},S=function(t){return h?(ro(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(c)s=t;else{if(!(a=co(t)))throw mo(no(t)+' is not iterable');if(oo(a)){for(r=0,n=uo(t);n>r;r++)if((o=S(t[r]))&&lo(So,o))return o;return new fo(!1)}s=ho(t,a)}for(u=s.next;!(d=ao(u,s)).done;){try{o=S(d.value)}catch(t){po(s,'throw',t)}if('object'==typeof o&&o&&lo(So,o))return o}return new fo(!1)},To=function(t,e,i){var s=bo(e);s in t?vo.f(t,s,go(0,i)):t[s]=i};Ss({target:'Object',stat:!0},{fromEntries:function(t){var e={};return yo(t,(function(t,i){To(e,t,i)}),{AS_ENTRIES:!0}),e}});var Eo=Qt.Object.fromEntries,ko={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},Po=st,wo=rn,$o=as,Ao=ia,xo=ei('toStringTag');for(var No in ko){var _o=Po[No],Do=_o&&_o.prototype;Do&&wo(Do)!==xo&&$o(Do,xo,No),Ao[No]=Ao.Array}var Ro,Io=Eo;class Lo{constructor(t,e=[],i,s,a,r){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=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let e=!1;this._xhr.onreadystatechange=()=>{var i,s,a,r,n,o,u,d;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(a=this._xhr)||void 0===a?void 0:a.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&&!e){e=!0;const t=Io(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(n=this._headersCb)||void 0===n||n.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(o=this._completeCb)||void 0===o||o.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(u=this._progressCb)||void 0===u||u.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Co{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,a,r,n){this.abort((()=>{let o=0;const u=Date.now();let d=0,l=0,h=0;const c=t=>{s(Co._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=F(p)),this._lastXhr=new Lo(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(t);const e=Date.now()-u;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==a||a()}),(t=>{if(t.length-o>n&&c(t),0===l)return void(l=Date.now());h=t.length-d;const e=Date.now()-l;h>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:h,duration:e,speed:8*h/(e/1e3)}),h=0,d=t.length,l=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((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=Co._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 Oo{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=F(i)),new Lo(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,u,d,l,h,c,p,m,f,S,b,v,g,y,T,E,k,P;const w=t.getElementsByTagName('SegmentBase')[0],$=w&&a(w,'indexRange').split('-'),A=w&&w.getElementsByTagName('Initialization')[0],x=A&&a(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const a=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,r=(i?i+'/':'')+(null===(l=null===(d=null===(u=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===u?void 0:u.childNodes)||void 0===d?void 0:d[0])||void 0===l?void 0:l.data),c=null!==(h=e.getAttribute('lang'))&&void 0!==h?h:void 0;r&&n.push({id:a,url:r,language:c})}return}const N=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),_=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const R=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=R?tt(R):void 0,r.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(S=t.attributes.getNamedItem('height'))||void 0===S?void 0:S.value),bandwidth:N,baseURL:_,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(v=null===(b=t.attributes.getNamedItem('codecs'))||void 0===b?void 0:b.value)&&void 0!==v?v:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:D,bufferSize:.1*N/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==(P=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==P?P:void 0})})),r.length?(this._representations=r,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 a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const u=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const d=t.refs[t.refs.length-1];d.toTime-d.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{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 r;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');r=e.end-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.end&&(a=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*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}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 Co({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.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 a=.1;if(s.toTime<i.end+a){const e=this._findRef(s.toTime);e&&e.toTime<i.end+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const a=i[e];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ro||(Ro={}));const Bo=[Ro.PAUSED,Ro.PLAYING];class Vo{constructor(e){this.videoState=new k(Ro.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new Y,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},this.handleManifestReady=t=>{var e,i,s;const a=[];for(const r of t){const t=null!==(i=null!==(e=r.name)&&void 0!==e?e:r.id)&&void 0!==i?i:r.height.toString(10),n=null!==(s=r.name&&Us(r.name))&&void 0!==s?s:T(r),o=r.bandwidth/1e3,u={width:r.width,height:r.height},d=r.fps;if(!n)continue;const l={id:t,quality:n,bitrate:o,size:u,fps:d};a.push({track:l,representation:r})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),this.videoState.setState(Ro.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&Bo.includes(e)&&this.seek(r.position,r.forcePrecise),e){case Ro.STOPPED:return this.videoState.startTransitionTo(Ro.MANIFEST_LOADED),void this.prepare();case Ro.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Ro.INITIAL_REPRESENTATION_SELECTED);case Ro.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Ro.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Ro.METADATA_LOADED:return this.videoState.startTransitionTo(Ro.READY),void this.dash.updateRefsForCurrentTime();case Ro.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Ro.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ro.PLAYING),this.playIfAllowed()));case Ro.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Ro.PAUSED),this.video.pause()):(null==a?void 0:a.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Ro.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Ro.PLAYING),this.playIfAllowed()):(null==a?void 0:a.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Ro.STOPPED&&(this.videoState.startTransitionTo(Ro.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(Ro.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Q(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(Cs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new J(this.video),this.dash=new Oo({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},a=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},r=Z(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.firstFrame$,e.firstFrameEvent$),this.subscription.add(r.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==l.Applying)&&(this.videoState.getState()===Ro.PLAYING||this.videoState.getState()===Ro.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(j(this.video,i.isLooped,s)),this.subscription.add(H(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,i,e),n(Os(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Ro.READY&&this.videoState.setState(Ro.READY)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ro.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(r.playing$.subscribe((()=>{this.videoState.setState(Ro.PLAYING),S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.loadedMetadata$.subscribe((()=>{this.videoState.setState(Ro.METADATA_LOADED)}),s)).add(r.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(t.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i;const s=this.currentRepresentation$.getValue(),r=this.representations$.getValue(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),l=a();let h;if(n&&this.params.desiredState.autoVideoTrackSwitching.setState(n.to),!l&&t.isNonNullable(o))h=o;else{const t=ea(this.video.buffered,1e3*this.video.currentTime),i=Math.min(t/this.params.tuning.dash.forwardBufferTarget,1);h=null===(e=Ls(r.map((({track:t})=>t)),{container:d,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:i,currentRepresentation:s}))||void 0===e?void 0:e.id}return t.isNonNullable(h)?null===(i=r.find((({track:t})=>t.id===h)))||void 0===i?void 0:i.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Ro.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Ro.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?t.height<=e.height:t===e))).subscribe((t=>{const e=ea(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!a())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Cs(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=ta(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){qs(this.video).then((t=>{t||(this.videoState.setState(Ro.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Mo,Fo,Uo,qo;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(Mo||(Mo={})),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'}(Fo||(Fo={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(Uo||(Uo={})),function(t){t.MP4='mp4',t.WEBM='webm'}(qo||(qo={}));class jo{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,this.queue=[],this.currentTask=null,this.onUpdateEnd=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueue',message:'Buffer appending or removal failed',thrown:t})}},this.buffer=e,this.buffer.addEventListener('updateend',this.onUpdateEnd)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}destroy(){this.buffer.removeEventListener('updateend',this.onUpdateEnd)}pull(){var t;if(this.buffer.updating||this.currentTask)return;const e=this.queue.shift();if(e){if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;try{this.execute(this.currentTask)}catch(t){this.currentTask.callback(!1),this.currentTask=null}}}execute(e){const{operation:i}=e;switch(i){case'append':try{this.buffer.appendBuffer(e.data)}catch(t){throw t instanceof DOMException&&'QuotaExceededError'===t.name&&this.bufferFull$.next(e.data.byteLength),t}break;case'remove':this.buffer.remove(e.from/1e3,e.to/1e3);break;default:t.assertNever(i)}}}var Ho;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Ho||(Ho={}));class Go{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new I,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=F(e));const i=yield R(e,{signal:this.abortAllController.signal}).catch(Yo);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetchRange=t.abortable(this.abortAllController.signal,async function*(e,i,s,{method:a=Ho.HEADER,onProgress:r,signal:n}={}){var o,u,d;let l=e;const h=new Headers;switch(a){case Ho.HEADER:h.append('Range',`${i}-${s}`);break;case Ho.PARAM:{const t=new URL(l,location.href);t.searchParams.append('bytes',`${i}-${s}`),l=t.toString();break}default:t.assertNever(a)}this.requestQuic&&(l=F(l));let c=this.abortAllController.signal;if(n){const e=new I;this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(n,'abort')).subscribe((()=>{e.abort()}))),(this.abortAllController.signal.aborted||n.aborted)&&e.abort(),c=e.signal}const p=t.now(),m=yield R(l,{headers:h,signal:c}).catch(Yo);if(null===(o=this.throughputEstimator)||void 0===o||o.addRawRtt(t.now()-p),!m)return null;if(!m.ok||!m.body)return Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));this.onHeadersReceived(m.headers);const[f,S]=m.body.tee(),b=f.getReader();null===(u=this.throughputEstimator)||void 0===u||u.trackStream(S);const v=parseInt(null!==(d=m.headers.get('Content-Length'))&&void 0!==d?d:'',10);let g=0;const y=new ArrayBuffer(v),T=new Uint8Array(y),E=new DataView(y);let k=!1;const P=t=>{k=!0,Yo(t)},w=t.abortable(c,async function*({done:e,value:i}){0===g&&this.lastRequestFirstBytes$.next(t.now()-p),e?null==r||r(E,g):i&&(T.set(i,g),g+=i.byteLength,null==r||r(E,g),yield null==b?void 0:b.read().then(w,P))}.bind(this));return yield null==b?void 0:b.read().then(w,P),k?null:y}.bind(this)),this.fetchRepresentation=t.abortable(this.abortAllController.signal,async function*(t,e,i=0){const{from:s,to:a}=t.initRange;let r,n,o=s,u=a,d=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,d=a+1===r,d&&(o=Math.min(r,s),u=Math.max(n,a))),o=Math.min(o,0),u+=i;const l=yield this.fetchRange(t.url,o,u,{method:Ho.PARAM});if(!l)return null;const h=new DataView(l,s-o,a-o+1);if(!e.validateData(h))throw new Error('Invalid media file');const c=e.parseInit(h);let p;if(d&&void 0!==r&&void 0!==n)p=new DataView(l,r-o,n-r+1);else{const i=e.getIndexRange(c);if(i){const e=yield this.fetchRange(t.url,i.from,i.to,{method:Ho.PARAM});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,c);return{dataView:new DataView(l),segments:m}}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=ta(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Yo=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Qo=new TextDecoder('ascii'),zo=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=Qo.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},Wo={validateData:t=>'ftyp'===Qo.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=zo(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),u=255&a();let d=n/r*1e3,l=t.byteOffset+t.byteLength+o;for(let t=0;t<u;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:Uo.NONE,time:{from:d,to:d+o},byte:{from:l,to:l+s-1}}),d+=o,l+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=zo(a);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Jo,Ko;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(Jo||(Jo={})),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'}(Ko||(Ko={}));const Xo={[Jo.EBML]:{type:Ko.Master},[Jo.EBMLVersion]:{type:Ko.UnsignedInteger},[Jo.EBMLReadVersion]:{type:Ko.UnsignedInteger},[Jo.EBMLMaxIDLength]:{type:Ko.UnsignedInteger},[Jo.EBMLMaxSizeLength]:{type:Ko.UnsignedInteger},[Jo.DocType]:{type:Ko.String},[Jo.DocTypeVersion]:{type:Ko.UnsignedInteger},[Jo.DocTypeReadVersion]:{type:Ko.UnsignedInteger},[Jo.Void]:{type:Ko.Binary},[Jo.Segment]:{type:Ko.Master},[Jo.SeekHead]:{type:Ko.Master},[Jo.Seek]:{type:Ko.Master},[Jo.SeekID]:{type:Ko.Binary},[Jo.SeekPosition]:{type:Ko.UnsignedInteger},[Jo.Info]:{type:Ko.Master},[Jo.TimestampScale]:{type:Ko.UnsignedInteger},[Jo.Duration]:{type:Ko.Float},[Jo.Tracks]:{type:Ko.Master},[Jo.Chapters]:{type:Ko.Master},[Jo.Cluster]:{type:Ko.Master},[Jo.Timestamp]:{type:Ko.UnsignedInteger},[Jo.SilentTracks]:{type:Ko.Master},[Jo.SilentTrackNumber]:{type:Ko.UnsignedInteger},[Jo.Position]:{type:Ko.UnsignedInteger},[Jo.PrevSize]:{type:Ko.UnsignedInteger},[Jo.SimpleBlock]:{type:Ko.Binary},[Jo.BlockGroup]:{type:Ko.Master},[Jo.EncryptedBlock]:{type:Ko.Binary},[Jo.Attachments]:{type:Ko.Master},[Jo.Tags]:{type:Ko.Master},[Jo.Cues]:{type:Ko.Master},[Jo.CuePoint]:{type:Ko.Master},[Jo.CueTime]:{type:Ko.UnsignedInteger},[Jo.CueTrackPositions]:{type:Ko.Master},[Jo.CueTrack]:{type:Ko.UnsignedInteger},[Jo.CueClusterPosition]:{type:Ko.UnsignedInteger},[Jo.CueRelativePosition]:{type:Ko.UnsignedInteger},[Jo.CueDuration]:{type:Ko.UnsignedInteger},[Jo.CueBlockNumber]:{type:Ko.UnsignedInteger},[Jo.CueCodecState]:{type:Ko.UnsignedInteger},[Jo.CueReference]:{type:Ko.Master},[Jo.CueRefTime]:{type:Ko.UnsignedInteger}},Zo=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=tu(t,i),a=s in Xo,r=a?Xo[s].type:Ko.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const u=new DataView(t.buffer,t.byteOffset+i+1,o-1),d=((n&255>>o)<<8*(o-1))+tu(u),l=i+o;let h;return h=l+d>t.byteLength?new DataView(t.buffer,t.byteOffset+l):new DataView(t.buffer,t.byteOffset+l,d),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:l,tagSize:l+d,value:h,valueSize:d}},tu=(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},eu=(e,i)=>{switch(i){case Ko.SignedInteger:return e.getInt8(0);case Ko.UnsignedInteger:return tu(e);case Ko.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Ko.String:return new TextDecoder('ascii').decode(e);case Ko.UTF8:return new TextDecoder('utf-8').decode(e);case Ko.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Ko.Master:case Ko.Binary:return e;default:t.assertNever(i)}},iu=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=Zo(s);if(!e(a))return;a.type===Ko.Master&&iu(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},su=[Jo.Info,Jo.SeekHead,Jo.Tracks,Jo.Chapters,Jo.Cluster,Jo.Cues,Jo.Attachments,Jo.Tags],au=[Jo.Timestamp,Jo.SilentTracks,Jo.SilentTrackNumber,Jo.Position,Jo.PrevSize,Jo.SimpleBlock,Jo.BlockGroup,Jo.EncryptedBlock],ru={validateData:t=>{if(t.getUint32(0)!==Jo.EBML)return!1;let e,i,s;const a=Zo(t);return iu(a.value,(({tag:t,type:a,value:r})=>(t===Jo.EBMLReadVersion?e=eu(r,a):t===Jo.DocType?i=eu(r,a):t===Jo.DocTypeReadVersion&&(s=eu(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,a,r,n,o,u=!1,d=!1,l=!1;return iu(e,(({tag:t,type:e,value:h,valueSize:c})=>{if(t===Jo.SeekID){const t=eu(h,e);o=tu(t)}else t!==Jo.SeekPosition&&(o=void 0);return t===Jo.Segment?(i=h.byteOffset,s=h.byteOffset+c):t===Jo.Info?u=!0:t===Jo.SeekHead?d=!0:t===Jo.TimestampScale?a=eu(h,e):t===Jo.Duration?r=eu(h,e):t===Jo.SeekPosition&&o===Jo.Cues?n=eu(h,e):u&&d&&su.includes(t)&&(l=!0),!l})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(r,'Failed to parse webm Segment duration'),a=null!=a?a:1e6,{segmentStart:Math.round(i/1e9*a*1e3),segmentEnd:Math.round(s/1e9*a*1e3),timeScale:a,segmentDuration:Math.round(r/1e9*a*1e3),cuesSeekPosition:n}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,a=!1;const r=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),n=[];let o;return iu(e,(({tag:t,type:e,value:i})=>{switch(t){case Jo.Cues:s=!0;break;case Jo.CuePoint:o&&r(o)&&n.push(o),o={};break;case Jo.CueTime:o&&(o.time=eu(i,e));break;case Jo.CueTrackPositions:break;case Jo.CueClusterPosition:o&&(o.position=eu(i,e));break;default:s&&su.includes(t)&&(a=!0)}return!(s&&a)})),o&&r(o)&&n.push(o),n.map(((t,e)=>{const{time:s,position:a}=t,r=n[e+1];return{status:Uo.NONE,time:{from:s,to:r?r.time:i.segmentDuration},byte:{from:i.segmentStart+a,to:r?i.segmentStart+r.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{iu(t,(s=>s.tag===Jo.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!au.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Jo.SimpleBlock,Jo.BlockGroup,Jo.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class nu{constructor(e,i,s,a,{fetcher:r,tuning:n,getCurrentPosition:o}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.activeSegments=new Set,this.downloadAbortController=new I,this.destroyAbortController=new I,this.allInitsLoaded=!1,this.bufferLimit=1/0,this.startWith=t.abortable(this.destroyAbortController.signal,async function*(e){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new jo(this.sourceBuffer),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>this.pruneBuffer(t)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t))));const s=yield this.fetcher.fetchRepresentation(i,this.containerParser).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:a,segments:r}=s;let n=0;for(const t of r)t.time.from-n>=300&&this.gaps.push({representation:i.id,from:n,to:t.time.from}),n=t.time.to;t.isNonNullable(i.duration)&&i.duration-n>=300&&this.gaps.push({representation:i.id,from:n,to:i.duration});const o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e,o),yield this.sourceBufferTaskQueue.append(o,this.destroyAbortController.signal),this.segments.set(e,r)}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,async function*(e){var i;if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=e,!this.initData.has(e))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);const s=yield this.fetcher.fetchRepresentation(i,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return;const{dataView:a,segments:r}=s,n=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);this.initData.set(e,n),this.segments.set(e,r)}const s=this.initData.get(e);t.assertNonNullable(s,`No init buffer for ${e}`),t.assertNonNullable(this.sourceBuffer,'SourceBuffer not inited yet'),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t.isNonNullable(this.playingRepresentationId)&&(null===(i=this.segments.get(this.playingRepresentationId))||void 0===i||i.forEach((t=>{t.status===Uo.FED?t.status=Uo.NONE:t.status===Uo.PARTIALLY_FED&&this.abortSegment(t)})));const a=this.getCurrentPosition();t.isNonNullable(a)&&this.maintain(a)}.bind(this)),this.fetcher=r,this.tuning=n,this.getCurrentPosition=o,this.container=s,s){case qo.MP4:this.containerParser=Wo;break;case qo.WEBM:this.containerParser=ru;break;default:t.assertNever(s)}this.initData=new Map,this.segments=new Map,this.representations=new Map(a.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new I,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer)||this.onLastSegment$.getValue())return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),t.assertNonNullable(s,`No segments for ${this.downloadingRepresentationId}`);const a=s.find((t=>e>=t.time.from&&e<t.time.to));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=ea(this.sourceBuffer.buffered,e);r=e+Math.min(t,this.tuning.representationSwitchForwardBufferGap)}let n=[];isFinite(this.bufferLimit)&&(t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e})(this.sourceBuffer.buffered)>=.8*this.bufferLimit?this.pruneBuffer(1/0):(n=this.selectForwardBufferSegments(s,r),n.length&&this.loadSegments(n,i)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&a&&a.status===Uo.FED&&!n.length&&ea(this.sourceBuffer.buffered,e)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const o=As(s,-1);o&&o.status===Uo.FED&&(this.fullyBuffered$.next(!0),a===o&&this.onLastSegment$.next(!0))}findSegmentStartTime(t){var e,i,s;const a=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!a)return;const r=this.segments.get(a);if(!r)return;const n=r.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===Uo.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.forwardBufferTarget));if(-1===i)return[];let s=0;const a=[];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!==Uo.NONE)break;a.push(i)}return a}async loadSegments(e,i){if(!e.length)return;const s=As(e,0).byte.from,a=As(e,-1).byte.to;for(const t of e)t.status=Uo.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,fedBytes:0});const{signal:r}=this.downloadAbortController;return this.segmentDownloadPromise=this.segmentDownloadPromise.then(t.abortable(this.destroyAbortController.signal,async function*(){if(r.aborted)for(const t of e)this.abortSegment(t);else yield this.fetcher.fetchRange(i.url,s,a,{method:Ho.PARAM,onProgress:(t,e)=>this.onSomeDataLoaded(t,i.id,s,e,r),signal:r})}.bind(this))).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}onSomeDataLoaded(t,e,i,s,a){var r;if(!this.activeSegments.size)return;const n=t=>{this.abortSegment(t.segment)},o=t=>{this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=Uo.FED,this.activeSegments.delete(t),this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback((()=>{try{this.detectGaps(e,[t.segment])}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}this.gapDetectionIdleCallback=null})))};for(const e of this.activeSegments){const{segment:u}=e,d=u.byte.to-u.byte.from+1;if(a.aborted)return void n(e);const l=u.byte.from>=i,h=u.byte.from<i+s,c=u.byte.to<=i+s;if(u.status===Uo.DOWNLOADING&&l&&h&&c){u.status=Uo.DOWNLOADED,this.activeSegments.delete(e);const r=new DataView(t.buffer,t.byteOffset+u.byte.from-i,Math.min(d,i+s-u.byte.from));this.sourceBufferTaskQueue.append(r,a).then((t=>t&&!a.aborted?o(e):n(e)))}else if(this.tuning.enableSubSegmentBufferFeeding&&l&&h){const l=Math.min(d,s-(u.byte.from-i));e.buffer=null!==(r=e.buffer)&&void 0!==r?r:new ArrayBuffer(d);const h=new DataView(e.buffer);for(let s=e.loadedBytes;s<l;s++)h.setUint8(s,t.getUint8(u.byte.from-i+s));e.loadedBytes=l;const c=new DataView(e.buffer,e.fedBytes,e.loadedBytes-e.fedBytes);if(d===e.loadedBytes&&e.fedBytes!==e.loadedBytes)u.status=Uo.DOWNLOADED,e.fedBytes=e.loadedBytes,this.sourceBufferTaskQueue.append(c,a).then((t=>t&&!a.aborted?o(e):n(e)));else if(e.loadedBytes>e.fedBytes){const t=this.containerParser.parseFeedableSegmentChunk(c);t&&(u.status=Uo.PARTIALLY_FED,e.fedBytes+=t.byteLength,this.sourceBufferTaskQueue.append(t,a).then((t=>{t&&!a.aborted||n(e)})))}}}}abortSegment(t){t.status===Uo.DOWNLOADING?t.status=Uo.NONE:t.status===Uo.PARTIALLY_FED&&this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=Uo.NONE));for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}async loadAllInits(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=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,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t,a),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})).finally((()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}async pruneBuffer(e){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let a=0,r=1/0,n=-1/0,o=!1;for(const t of s){if(t.time.to>=i||a>=e)break;t.status===Uo.FED&&(r=Math.min(r,t.time.from),n=Math.max(n,t.time.to),a+=t.byte.to-t.byte.from)}if(o=isFinite(r)&&isFinite(n)&&(a>=e||e===1/0),!o){a=0,r=1/0,n=-1/0;for(const t of s)t.status===Uo.FED&&t.time.from>i+this.tuning.forwardBufferTarget&&(r=Math.min(r,t.time.from),n=Math.max(n,t.time.to),a+=t.byte.to-t.byte.from)}return o=isFinite(r)&&isFinite(n)&&(a>=e||e===1/0),!!o&&(await this.sourceBufferTaskQueue.remove(r,n/1e3),!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})}}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=this.segments.get(this.playingRepresentationId);if(t.isNullable(e))return;const i=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);i.push({from:e,to:s})}const s=this.tuning.segmentTimelineTolerance;for(const t of e){const e=i.some((e=>e.from-s<=t.time.from&&e.to+s>=t.time.to));t.status!==Uo.FED||e||(t.status=Uo.NONE)}}}const ou=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*600*1e3+60*e(null==i?void 0:i[6],s)*600*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},uu=['timeupdate','progress','play','seeked','stalled'];var du,lu;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(du||(du={}));class hu{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new k(du.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new I,this.initManifest=t.abortable(this.destroyController.signal,async function*(e,i){this.element=e,this.state$.startTransitionTo(du.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(i);if(!s)return null;let a;try{a=((e,i)=>{var s,a,r,n,o,u,d,l,h,c,p,m,f,S,b,v,g,y,T,E,k,P,w,$;const A={video:[],audio:[],text:[]},x=(new DOMParser).parseFromString(e,'application/xml').children[0],N=x.getElementsByTagName('Period')[0],_=N.children;let D;const R=x.getAttribute('mediaPresentationDuration'),I=N.getAttribute('duration');if(R)D=ou(R);else if(I){const e=ou(I);t.isNonNullable(e)&&(D=e)}let L=0;const C=null!==(a=null===(s=x.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==a?a:[],O=C.includes(Fo.WEBM_AS_IN_FFMPEG)||C.includes(Fo.WEBM_AS_IN_SPEC)?qo.WEBM:qo.MP4;for(const t of _){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),a=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==e?void 0:e.split('/')[0],x=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],N=t.querySelectorAll('Representation');for(const r of N){const n=null!==(u=r.getAttribute('mimeType'))&&void 0!==u?u:e,o=null!==(l=null!==(d=r.getAttribute('codecs'))&&void 0!==d?d:s)&&void 0!==l?l:'',N=null!==(c=null!==(h=r.getAttribute('contentType'))&&void 0!==h?h:null==n?void 0:n.split('/')[0])&&void 0!==c?c:a,_=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],R=parseInt(null!==(f=r.getAttribute('width'))&&void 0!==f?f:'',10),I=parseInt(null!==(S=r.getAttribute('height'))&&void 0!==S?S:'',10),O=parseInt(null!==(b=r.getAttribute('bandwidth'))&&void 0!==b?b:'',10)/1e3,B=null!==(v=r.getAttribute('frameRate'))&&void 0!==v?v:'',V=null!==(g=r.getAttribute('quality'))&&void 0!==g?g:void 0,M=B?tt(B):void 0,F=`${null!==(y=r.getAttribute('id'))&&void 0!==y?y:(L++).toString(10)}@${'video'===N?`${I}p`:'audio'===N?`${O}Kbps`:o}`,U=null!==(k=null===(E=null===(T=r.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',q=new URL(U,i).toString(),j=[...C,...x,..._],H=null!==(w=null===(P=r.querySelector('SegmentBase Initialization'))||void 0===P?void 0:P.getAttribute('range'))&&void 0!==w?w:'',[G,Y]=H.split('-').map((t=>parseInt(t,10))),Q={from:G,to:Y},z=null===($=r.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[W,J]=z?z.split('-').map((t=>parseInt(t,10))):[],K=z?{from:W,to:J}:void 0;if(!N||!n)continue;const X={video:Mo.VIDEO,audio:Mo.AUDIO,text:Mo.TEXT}[N];X&&A[X].push({id:F,kind:X,duration:D,profiles:j,initRange:Q,indexRange:K,bitrate:O,mime:n,codecs:o,width:R,height:I,fps:M,quality:V,url:q})}}return{container:O,representations:A}})(null!=s?s:'',i)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!a)return null;const r=({mime:t,codecs:i})=>{var s,a,r;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(r=null===(a=window.MediaSource)||void 0===a?void 0:a.isTypeSupported)||void 0===r?void 0:r.call(a,`${t}; codecs="${i}"`)))};return this.manifest={...a,representations:Io(Object.entries(a.representations).map((([t,e])=>[t,e.filter(r)])))},this.manifest.representations.video.length?this.state$.setState(du.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,async function*(e,i){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(du.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning.dash,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new nu(Mo.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.audioBufferManager=new nu(Mo.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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(t.merge(this.forceEnded$,t.merge(this.videoBufferManager.onLastSegment$,this.audioBufferManager.onLastSegment$,this.videoBufferManager.fullyBuffered$,this.audioBufferManager.fullyBuffered$).pipe(t.filter((()=>!(!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;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(t.merge(this.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(e),this.audioBufferManager.startWith(i)]),this.state$.setState(du.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...uu.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{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()}.bind(this)),this.tick=()=>{if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const e=1e3*this.element.currentTime;this.videoBufferManager.maintain(e),this.audioBufferManager.maintain(e),!this.videoBufferManager.gaps.length&&!this.audioBufferManager.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(e,i){const s={[Mo.VIDEO]:this.videoBufferManager,[Mo.AUDIO]:this.audioBufferManager,[Mo.TEXT]:null}[e];return t.assertNonNullable(s),s.switchTo(i)}seek(e,i){var s,a;let r;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),t.assertNonNullable(this.audioBufferManager),this.videoBufferManager.abort(),this.audioBufferManager.abort(),r=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(a=this.audioBufferManager.findSegmentStartTime(e))&&void 0!==a?a:e),this.videoBufferManager.maintain(r),this.audioBufferManager.maintain(r),this.element.currentTime=r/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(du.NONE)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of[this.videoBufferManager,this.audioBufferManager])for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(lu||(lu={}));const cu=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{var n;const o=null!==(n=r?Us(r):void 0)&&void 0!==n?n:T({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:a}},pu=(t,e,i)=>{var s;const a=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return null!==(s=As(t,Math.round(t.length*a/e.length)))&&void 0!==s?s:As(t,-1)};class mu{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(lu.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new Y,this.videoTracks=[],this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(a.state===l.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==lu.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(a.position,a.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===lu.STOPPED)return this.videoState.startTransitionTo(lu.READY),void this.prepare();switch(e){case lu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(lu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(lu.PLAYING),this.playIfAllowed()));case lu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(lu.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case lu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(lu.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==lu.STOPPED&&(this.videoState.startTransitionTo(lu.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(lu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=Q(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Cs(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=Z(this.video),a=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,a));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.firstFrame$,e.firstFrameEvent$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(j(this.video,i.isLooped,a)),this.subscription.add(H(this.video,i.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),r(Os(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(lu.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),a)).add(s.pause$.subscribe((()=>{this.videoState.setState(lu.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),a)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===lu.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===du.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(lu.READY)}))),this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var e,s,a;const r=this.player.state$.getState(),n=this.player.state$.getTransition();if(r===du.NONE||!this.videoTracks.length)return;const o=r===du.MANIFEST_LOADED&&!n,u=i.autoVideoTrackSwitching.getState(),d=i.videoTrack.getState(),l=null===(e=this.videoTracks.find((({track:{id:t}})=>t===d)))||void 0===e?void 0:e.track;i.autoVideoTrackSwitching.getTransition()&&i.autoVideoTrackSwitching.setState(u);const h=ea(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=Ls(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),forwardBufferHealth:c}),m=u?null!=p?p:l:null!=l?l:p;if(o){const e=m&&(null===(s=this.videoTracks.find((({track:t})=>t===m)))||void 0===s?void 0:s.representation);t.assertNonNullable(e);const i=pu(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),e);t.assertNonNullable(i),this.player.initRepresentations(e.id,i.id)}else{const t=m&&(null===(a=this.videoTracks.find((({track:t})=>t===m)))||void 0===a?void 0:a.representation);if(t){const e=pu(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(Mo.VIDEO,t.id),e&&this.player.switchRepresentation(Mo.AUDIO,e.id)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,a))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);if(t){this.videoTracks=[];for(const e of t.representations.video){const t=cu(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,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){qs(this.video).then((t=>{t||(this.videoState.setState(lu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const fu={};var Su;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Su||(Su={}));const bu=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class vu{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(Su.INITIALIZING),this.textTracksManager=new Y,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!==Su.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&this.seek(a.position),i){case exports.PlaybackState.STOPPED:switch(e){case Su.STOPPED:break;case Su.READY:case Su.PLAYING:case Su.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Su.PLAYING:break;case Su.STOPPED:this.prepare();break;case Su.READY:case Su.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Su.PAUSED:break;case Su.STOPPED:this.prepare();break;case Su.READY:this.videoState.setState(Su.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Su.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Cs(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},s=window.setTimeout((()=>e('timeout')),5e3);Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(fu.Hls=e.default,fu.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(fu.Hls,'hls.js not loaded'),this.hls=new fu.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Su.STOPPED)}subscribe(){t.assertNonNullable(fu.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=Z(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,i.position$),r(a.durationChange$,i.duration$),r(a.ended$,i.endedEvent$),r(a.looped$,i.loopedEvent$),r(a.error$,i.error$),r(a.isBuffering$,i.isBuffering$),r(a.currentBuffer$,i.currentBuffer$),r(a.firstBytes$,i.firstBytesEvent$),r(a.firstFrame$,i.firstFrameEvent$),r(a.seeked$,i.seekedEvent$),this.subscription.add(j(this.video,e.isLooped,s)),this.subscription.add(H(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(bu(this.hls,fu.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Su.PLAYING),S(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Su.PAUSED),S(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Su.READY&&this.videoState.setState(Su.READY),this.videoState.getState()===Su.PLAYING&&this.playIfAllowed()}),s)),r(bu(this.hls,fu.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const a=e.name||e.height.toString(10),{width:r,height:n}=e,o=null!==(s=Us(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:T({width:r,height:n});if(!o)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,d={id:a.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:r,height:n},fps:u};return this.trackLevels.set(a,{track:d,level:e}),t.push(d),t}),[])))),i.availableVideoTracks$),r(bu(this.hls,fu.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>Cs(t)))),i.hostname$),this.subscription.add(q(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const n=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},o=bu(this.hls,fu.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>n(this.hls.levels[t]))));o.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(q(e.videoTrack,(()=>{var t;return null===(t=n(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const a=this.hls.levels.indexOf(s),r=this.hls.currentLevel,n=this.hls.levels[r];!n||s.bitrate>n.bitrate?this.hls.nextLevel=a:(this.hls.loadLevel=a,this.hls.loadLevel=a)}),{changed$:o.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),r(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(Su.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Su.PLAYING);await qs(this.video)||(this.videoState.setState(Su.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Su.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Su.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const gu=t=>{let e=null;if(t.QUALITY&&(e=Us(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=T({width:i,height:s})}return null!=e?e:null},yu=async(t,e=t)=>{var i;const s=await R(t),a=(await s.text()).split('\n'),r=[];for(let t=0;t<a.length;t++){const s=a[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=Io(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,u=gu(n);let d;n.BANDWIDTH&&(d=parseInt(n.BANDWIDTH,10)/1e3||void 0),!d&&n['AVERAGE-BANDWIDTH']&&(d=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const l=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let h;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(h={width:t,height:e})}const c=new URL(a[++t],e).toString();u&&r.push({id:o,quality:u,url:c,bandwidth:d,size:h,fps:l})}return r};var Tu,Eu,ku;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Tu||(Tu={}));class Pu{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new k(Tu.STOPPED),this.textTracksManager=new Y,this.manifests$=new t.ValueSubject([]),this.liveOffset=new z,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Tu.STOPPED&&(this.videoState.startTransitionTo(Tu.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(Tu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Tu.STOPPED)return this.videoState.startTransitionTo(Tu.READY),void this.prepare();if(a||r){const t=this.videoState.getState();return this.videoState.setState(Tu.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(n.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested)return this.videoState.startTransitionTo(Tu.READY),this.seek(n.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case Tu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Tu.PAUSED),this.liveOffset.pause(),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Tu.PLAYING),this.playIfAllowed()));case Tu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Tu.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Tu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Tu.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Tu.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),yu(f(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Cs(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),n=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=a?'master':n;return a&&!r&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},a=Z(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.ended$,e.endedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.firstBytes$,e.firstBytesEvent$),r(a.firstFrame$,e.firstFrameEvent$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(H(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Tu.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Tu.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Tu.READY&&this.videoState.setState(Tu.READY),this.videoState.getState()===Tu.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Cs(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Tu.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===l.Requested&&this.seek(e.position)}),s)),this.subscription.add(a.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=f(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',i),this.video.load(),(async t=>{const e=await R(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0})(i).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}playIfAllowed(){qs(this.video).then((t=>{t||(this.videoState.setState(Tu.PAUSED),this.liveOffset.pause(),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Eu||(Eu={}));class wu{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(Eu.STOPPED),this.textTracksManager=new Y,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Eu.STOPPED&&(this.videoState.startTransitionTo(Eu.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(Eu.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Eu.STOPPED)return this.videoState.startTransitionTo(Eu.READY),void this.prepare();if(a||r){const t=this.videoState.getState();this.videoState.setState(Eu.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(n.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&this.seek(n.position),e){case Eu.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Eu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Eu.PLAYING),this.playIfAllowed()));case Eu.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Eu.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Eu.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Eu.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Eu.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Cs(this.params.source.url)),yu(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,a=i.getState(),r=s.getTransition(),n=null!==(e=null!==(t=null==r?void 0:r.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=a?'master':n;return a&&!r&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},a=Z(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.firstBytes$,e.firstBytesEvent$),r(a.firstFrame$,e.firstFrameEvent$),r(a.seeked$,e.seekedEvent$),this.subscription.add(j(this.video,i.isLooped,s)),this.subscription.add(H(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Eu.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Eu.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Eu.READY&&this.videoState.setState(Eu.READY),this.videoState.getState()===Eu.PLAYING&&this.playIfAllowed()}),s).add(a.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Cs(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),i&&i.from===Eu.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===l.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){qs(this.video).then((t=>{t||(this.videoState.setState(Eu.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ku||(ku={}));class $u{constructor(e){this.subscription=new t.Subscription,this.videoState=new k(ku.STOPPED),this.trackUrls={},this.textTracksManager=new Y,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==ku.STOPPED&&(this.videoState.startTransitionTo(ku.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(ku.STOPPED),S(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(e===ku.STOPPED)return this.videoState.startTransitionTo(ku.READY),void this.prepare();if(a){const{currentTime:t}=this.video;return this.prepare(),void(r.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&this.seek(r.position),e){case ku.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(ku.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ku.PLAYING),this.playIfAllowed()));case ku.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ku.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&S(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ku.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ku.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=Q(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},a=Z(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(a.timeUpdate$,e.position$),r(a.durationChange$,e.duration$),r(a.ended$,e.endedEvent$),r(a.looped$,e.loopedEvent$),r(a.error$,e.error$),r(a.isBuffering$,e.isBuffering$),r(a.currentBuffer$,e.currentBuffer$),r(a.firstBytes$,e.firstBytesEvent$),r(a.firstFrame$,e.firstFrameEvent$),r(a.seeked$,e.seekedEvent$),this.subscription.add(j(this.video,i.isLooped,s)),this.subscription.add(H(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(ku.PLAYING),S(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(ku.PAUSED),S(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(a.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===ku.READY&&this.videoState.setState(ku.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===ku.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:a}=this.trackUrls[s];t.assertNonNullable(a,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(a=F(a)),this.video.setAttribute('src',a),this.video.load(),this.params.output.hostname$.next(Cs(a))}playIfAllowed(){qs(this.video).then((t=>{t||(this.videoState.setState(ku.PAUSED),S(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class Au{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 xu,Nu,_u,Du,Ru,Iu,Lu,Cu,Ou,Bu,Vu,Mu,Fu,Uu,qu,ju,Hu;const Gu=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),Yu=(null===(xu=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===xu?void 0:xu.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Qu=document.createElement('video'),zu={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(_u=null===(Nu=window.SourceBuffer)||void 0===Nu?void 0:Nu.prototype)||void 0===_u?void 0:_u.appendBuffer)),hls:Boolean((null===(Du=Qu.canPlayType)||void 0===Du?void 0:Du.call(Qu,'application/x-mpegurl'))||(null===(Ru=Qu.canPlayType)||void 0===Ru?void 0:Ru.call(Qu,'vnd.apple.mpegURL')))},Wu={mp4:Boolean(null===(Iu=Qu.canPlayType)||void 0===Iu?void 0:Iu.call(Qu,'video/mp4')),webm:Boolean(null===(Lu=Qu.canPlayType)||void 0===Lu?void 0:Lu.call(Qu,'video/webm'))},Ju={h264:Boolean(null===(Ou=null===(Cu=window.MediaSource)||void 0===Cu?void 0:Cu.isTypeSupported)||void 0===Ou?void 0:Ou.call(Cu,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Vu=null===(Bu=window.MediaSource)||void 0===Bu?void 0:Bu.isTypeSupported)||void 0===Vu?void 0:Vu.call(Bu,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Fu=null===(Mu=window.MediaSource)||void 0===Mu?void 0:Mu.isTypeSupported)||void 0===Fu?void 0:Fu.call(Mu,'video/webm; codecs="vp9"')),aac:Boolean(null===(qu=null===(Uu=window.MediaSource)||void 0===Uu?void 0:Uu.isTypeSupported)||void 0===qu?void 0:qu.call(Uu,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Hu=null===(ju=window.MediaSource)||void 0===ju?void 0:ju.isTypeSupported)||void 0===Hu?void 0:Hu.call(ju,'audio/webm; codecs="opus"'))},Ku=(Ju.h264||Ju.h265)&&Ju.aac,Xu=!Gu,Zu=Yu||Gu,td=!zu.hls||!Zu;const ed=3e4,id=18e4,sd=3,ad=100,rd={cacheDuration:12e4},nd={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},od={maxPausedTime:3e4},ud={maxPausedTime:3e4};class dd{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new Au(s.filter((i=>t.isNonNullable(e.sources[i]))).filter((e=>{switch(e){case exports.VideoFormat.DASH:return zu.mse&&Wu.mp4&&Ku&&Xu;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return zu.mse&&Wu.mp4&&Ku;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return zu.mse&&Wu.webm&&Ju.vp9&&Ju.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return zu.mse&&Wu.mp4&&Ku;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return zu.hls&&Wu.mp4&&Zu;case exports.VideoFormat.HLS_JS:return zu.mse&&Wu.mp4&&Ku&&td;case exports.VideoFormat.MPEG:return Wu.mp4;default:return t.assertNever(e)}}))),this.chromecastFormatsIterator=new Au(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=this.params.desiredState.seekState.getState();e.state!==l.Requested&&e.state!==l.Applying||this.params.desiredState.seekState.setState({...e,state:l.Requested}),t.destroy();const i=this.providerOutput.isBuffering$;i.getValue()||i.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case n.SCREEN:return this.createScreenProvider(i);case n.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:a}=this.params,r=this.providerOutput;switch(e){case exports.VideoFormat.DASH:{const n=i[e];return t.assertNonNullable(n),new Vo({container:s,source:n,desiredState:a,output:r,config:rd,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const n=i[e];return t.assertNonNullable(n),new mu({container:s,source:n,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const n=i[e];return t.assertNonNullable(n),new Fs({container:s,source:n,desiredState:a,output:r,format:e,config:ud,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const n=i[e];return t.assertNonNullable(n),new wu({container:s,source:n,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const n=i[e];return t.assertNonNullable(n),new Pu({container:s,source:n,desiredState:a,output:r,config:od,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const n=i[e];return t.assertNonNullable(n),new vu({container:s,source:n,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const n=i[e];return t.assertNonNullable(n),new $u({container:s,source:n,desiredState:a,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const n=i[e];return t.assertNonNullable(n),new Zs({container:s,source:n,desiredState:a,output:r,config:nd,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:a,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(o),new w({connection:o,meta:r,container:s,source:i,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?n.CHROMECAST:n.SCREEN}chooseFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case n.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.next();case n.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case n.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case n.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var a;return s.add(t.merge(this.providerOutput.error$,(a={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:ed,position$:this.providerOutput.position$,providerChanged$:this.current$},new t.Observable((e=>{const i=new t.Subscription,s=t.timeout(a.maxTransitionInterval),r=new t.ValueSubject(void 0);t.merge(a.desiredPlaybackState$.stateChangeStarted$.pipe(t.mapTo(s)),a.desiredPlaybackState$.stateChangeEnded$.pipe(t.mapTo(void 0)),a.providerChanged$.pipe(t.map((()=>r.getValue())))).subscribe(r);const n=new t.Subscription;return i.add(n),i.add(r.subscribe((t=>{n.unsubscribe(),t&&n.add(t.subscribe(e))}))),i}))).pipe(t.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(ad,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===n.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+id?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%sd}))),s}}const ld=(t,e,i)=>i*e+(1-i)*t;class hd{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.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Rs(`raw_${s}`),this.smoothedSeries$=new Rs(`smoothed_${s}`),this.reportedSeries$=new Rs(`reported_${s}`)}next(e){this.slow=ld(this.slow,e,this.params.emaAlphaSlow),this.fast=ld(this.fast,e,this.params.emaAlphaFast);const i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast),this.smoothed$.next(this.smoothed),(t.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed)),this.rawSeries$.next(e),this.smoothedSeries$.next(this.smoothed)}}var cd;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(cd||(cd={}));const pd=new Map;let md=cd.RUNTIME;const fd=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(fd,'test'),localStorage.removeItem(fd),md=cd.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(fd),md=cd.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;md=cd.RUNTIME}}})();const Sd=(e,i)=>{switch(md){case cd.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case cd.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case cd.RUNTIME:return void pd.set(e,i);default:t.assertNever(md)}},bd=window.navigator.connection,vd=()=>{const e=null==bd?void 0:bd.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},gd=()=>{const e=null==bd?void 0:bd.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},yd=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Td{constructor(e){var i,s;this.subscription=new t.Subscription,this.tuningConfig=e;const a=Td.load('one_video_throughput')||(e.useBrowserEstimation?vd():void 0)||5e3,r=null!==(s=null!==(i=Td.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?gd():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(a),this.rtt$=new t.ValueSubject(r),this.rttAdjustedThroughput$=new t.ValueSubject(yd(a,r,e.rttPenaltyRequestSize)),this.throughput=new hd({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new hd({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=vd();e&&this.throughput.next(e);const i=gd();t.isNonNullable(i)&&this.rtt.next(i)};bd&&'onchange'in bd&&this.subscription.add(t.fromEvent(bd,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Sd('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Sd('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>yd(t,i,e.rttPenaltyRequestSize))),t.filter((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(e){let i=0,s=t.now();const a=new t.Subscription;switch(this.subscription.add(a),e.readyState){case 4:break;case 3:case 2:a.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:a.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}a.add(t.fromEvent(e,'loadend').subscribe((r=>{if(200===e.status){const e=r.loaded,a=t.now(),n=e-i,o=a-s;this.addRawSpeed(n,o)}a.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const a=t.now();let r=0,n=t.now();const o=t=>{i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=async({done:e,value:d})=>{e?this.addRawSpeed(s,t.now()-a):d&&(s+=d.byteLength,r+=d.byteLength,r>=this.tuningConfig.streamMinSampleSize&&t.now()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,t.now()-n),r=0,n=t.now()),await(null==i?void 0:i.read().then(u,o)))};null==i||i.read().then(u,o)}addRawSpeed(t,e){if(Td.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(e){var i;const s=(e=>{var i,s;switch(md){case cd.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case cd.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case cd.RUNTIME:return pd.get(e);default:t.assertNever(md)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Ed={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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1};const kd=(e=(t=>t))=>({playbackState:i,seekState:s,playbackAbort$:a,looped$:r,position$:n})=>new t.Observable((o=>{let u;const d=i.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),h=i.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),c=s.stateChangeEnded$.pipe(t.filter((({to:t})=>{var e,s;return t.state===l.Requested&&(null!==(s=null===(e=i.getTransition())||void 0===e?void 0:e.from)&&void 0!==s?s:i.getState())===exports.PlaybackState.PLAYING}))),p=s.stateChangeEnded$.pipe(t.filter((({from:t,to:e})=>{var s,a;return t.state===l.Applying&&e.state===l.None&&(null!==(a=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==a?a:i.getState())===exports.PlaybackState.PLAYING}))),m=t.merge(d,p).pipe(t.map((()=>e(n.getValue())))),f=t.merge(t.merge(h,c,a).pipe(t.map((()=>e(n.getValue())))),r.pipe(t.map(e)));return(new t.Subscription).add(m.subscribe((t=>{u=e(t)}))).add(f.subscribe((i=>{const s=e(i);if(t.isNullable(u)||u===s)return;const a={start:u,end:s};u=void 0,o.next(a)})))})),Pd=kd((t=>t)),wd=kd((t=>Math.round(1e3*t)+Date.now())),$d={[n.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[n.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new k(exports.PlaybackState.STOPPED),seekState:new k({state:l.None}),volume:new k({volume:1,muted:!1}),videoTrack:new k(void 0),autoVideoTrackSwitching:new k(!0),autoVideoTrackLimits:new k({}),isLooped:new k(!1),externalTextTracks:new k([]),currentTextTrack:new k(void 0),textTrackCuesSettings:new k({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={started$:new t.Subject,startAttempt$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:_s},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Ed)){const s=Ed[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:null!=a?a:s}return e})(e),this.chromecastInitializer=new h({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Td(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}>`})))),a=`Player.${String(e)}`,r=`Exception calling ${a} (${s.join(', ')})`;throw this.events.fatalError$.next({id:a,message:r,thrown:t}),t}}}})}initVideo(e){var i,s;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new dd({screenFormatsPriority:[...$d[n.SCREEN].live,...$d[n.SCREEN].vod],chromecastFormatsPriority:[...$d[n.CHROMECAST].live,...$d[n.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:l.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===l.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===l.Requested?this.desiredState.seekState.setState({...t,state:l.Applying}):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===l.Applying&&(this.desiredState.seekState.setState({state:l.None}),this.events.seeked$.next())}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>E(t)?1:E(e)?-1:v(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekState:e,position$:i})=>t.merge(e.stateChangeEnded$.pipe(t.map((({to:t})=>{var e;return t.state===l.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>e.getState().state===l.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(t.map((t=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let a=0;const r=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),a=i.getValue()||s.getValue();return t&&!a})),t.filterChanged());this.subscription.add(r.subscribe((t=>{t?a=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})));const n=new t.Subscription;this.subscription.add(n);const o=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),n.unsubscribe(),e){case!0:n.add(wd({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:n.add(Pd({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=Ls(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),Ns={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{xs=t})),this.providerContainer.current$.subscribe((({type:t})=>Ds('provider',t))),i.duration$.subscribe((t=>Ds('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>Ds('tracks',t))),this.events.fatalError$.subscribe(new Rs('fatalError')),this.events.managedError$.subscribe(new Rs('managedError')),i.position$.subscribe(new Rs('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new Rs('quality')),i.currentBuffer$.subscribe(new Rs('buffer')),i.isBuffering$.subscribe(new Rs('isBuffering'))].forEach((t=>this.subscription.add(t))),Ds('codecs',Object.keys(Ju).filter((t=>Ju[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.50';