@vkontakte/videoplayer-core 2.0.77 → 2.0.78

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 (108) hide show
  1. package/es2015.cjs.js +6 -4
  2. package/es2015.esm.js +6 -4
  3. package/es2018.cjs.js +6 -4
  4. package/es2018.esm.js +6 -4
  5. package/esnext.cjs.js +6 -4
  6. package/esnext.esm.js +6 -4
  7. package/index.d.ts +606 -8
  8. package/package.json +4 -4
  9. package/build/polyfills/runtime/abortableFetch.d.ts +0 -4
  10. package/build/polyfills/runtime/idleCallback.d.ts +0 -2
  11. package/env.d.ts +0 -2
  12. package/es2015.cjs.d.ts +0 -11
  13. package/es2015.esm.d.ts +0 -11
  14. package/es2018.cjs.d.ts +0 -11
  15. package/es2018.esm.d.ts +0 -11
  16. package/esnext.esm.d.ts +0 -11
  17. package/packages/core/src/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +0 -23
  18. package/packages/core/src/providers/DashIFProvider/dashjsTypes.d.ts +0 -37
  19. package/packages/core/src/providers/DashLiveProvider/types.d.ts +0 -14
  20. package/packages/core/src/providers/DashLiveProvider/utils/FilesFetcher.d.ts +0 -25
  21. package/packages/core/src/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -135
  22. package/packages/core/src/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -33
  23. package/packages/core/src/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +0 -42
  24. package/packages/core/src/providers/DashProvider/types.d.ts +0 -33
  25. package/packages/core/src/providers/DashProvider/utils/DashLite.d.ts +0 -60
  26. package/packages/core/src/providers/DashProvider/utils/stream.d.ts +0 -39
  27. package/packages/core/src/providers/DashProvider/utils/xhr2.d.ts +0 -15
  28. package/packages/core/src/providers/DashVKProvider/lib/buffer.d.ts +0 -72
  29. package/packages/core/src/providers/DashVKProvider/lib/ebml.d.ts +0 -71
  30. package/packages/core/src/providers/DashVKProvider/lib/fetcher.d.ts +0 -43
  31. package/packages/core/src/providers/DashVKProvider/lib/isobmff.d.ts +0 -13
  32. package/packages/core/src/providers/DashVKProvider/lib/mpd.d.ts +0 -2
  33. package/packages/core/src/providers/DashVKProvider/lib/player.d.ts +0 -47
  34. package/packages/core/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +0 -18
  35. package/packages/core/src/providers/DashVKProvider/lib/types.d.ts +0 -92
  36. package/packages/core/src/providers/DashVKProvider/lib/webm.d.ts +0 -3
  37. package/packages/core/src/providers/ProviderContainer/types.d.ts +0 -20
  38. package/packages/core/src/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +0 -9
  39. package/packages/core/src/providers/types.d.ts +0 -64
  40. package/packages/core/src/providers/utils/LiveOffset/index.d.ts +0 -14
  41. package/packages/core/src/providers/utils/LiveOffset/types.d.ts +0 -10
  42. package/packages/core/src/providers/utils/extractConnectionHeaders.d.ts +0 -6
  43. package/packages/core/src/utils/StateMachine/types.d.ts +0 -56
  44. package/packages/core/src/utils/StatefulIterator/StatefulIterator.spec.d.ts +0 -1
  45. package/packages/core/src/utils/buffer/HttpVideoBuffer.d.ts +0 -14
  46. package/packages/core/src/utils/buffer/getTotalBufferDuration.d.ts +0 -3
  47. package/packages/core/src/utils/buffer/isPositionBuffered.d.ts +0 -3
  48. package/packages/core/src/utils/buffer/types.d.ts +0 -4
  49. package/packages/core/src/utils/link.d.ts +0 -2
  50. package/packages/core/src/utils/quality/quality.spec.d.ts +0 -1
  51. package/player/Player.d.ts +0 -111
  52. package/player/types.d.ts +0 -430
  53. package/player/utils/optimisticPosition.d.ts +0 -12
  54. package/player/utils/selectContainer.d.ts +0 -3
  55. package/player/utils/watchCoverage.d.ts +0 -12
  56. package/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +0 -31
  57. package/providers/ChromecastProvider/index.d.ts +0 -33
  58. package/providers/DashIFProvider/BigRequestLoader.d.ts +0 -41
  59. package/providers/DashIFProvider/endOfStreamHack.d.ts +0 -3
  60. package/providers/DashIFProvider/index.d.ts +0 -37
  61. package/providers/DashIFProvider/observableManifestLoader.d.ts +0 -11
  62. package/providers/DashIFProvider/requestQuic.d.ts +0 -3
  63. package/providers/DashIFProvider/stripRangeHeader.d.ts +0 -3
  64. package/providers/DashLiveProvider/DashLiveProvider.d.ts +0 -36
  65. package/providers/DashLiveProvider/index.d.ts +0 -2
  66. package/providers/DashProvider/DashProvider.d.ts +0 -32
  67. package/providers/DashProvider/index.d.ts +0 -2
  68. package/providers/DashVKProvider/index.d.ts +0 -23
  69. package/providers/DashVKProvider/lib/player.d.ts +0 -47
  70. package/providers/DashVKProvider/lib/types.d.ts +0 -92
  71. package/providers/HlsJsProvider/index.d.ts +0 -24
  72. package/providers/HlsLiveProvider/index.d.ts +0 -28
  73. package/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +0 -3
  74. package/providers/HlsProvider/index.d.ts +0 -20
  75. package/providers/HlsProvider/qualityExtractor.d.ts +0 -12
  76. package/providers/MpegProvider/index.d.ts +0 -19
  77. package/providers/ProviderContainer/index.d.ts +0 -69
  78. package/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -4
  79. package/providers/ProviderContainer/utils/playbackHangup.d.ts +0 -11
  80. package/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +0 -188
  81. package/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +0 -60
  82. package/providers/utils/HtmlVideoTextTrackManager.d.ts +0 -23
  83. package/providers/utils/addQuicParam.d.ts +0 -2
  84. package/providers/utils/forcePlay.d.ts +0 -7
  85. package/providers/utils/generateLiveUrl.d.ts +0 -7
  86. package/providers/utils/initVideoInContainer.d.ts +0 -2
  87. package/providers/utils/observableVideo.d.ts +0 -24
  88. package/providers/utils/okQualityStringToVideoQuality.d.ts +0 -3
  89. package/providers/utils/parseFps.d.ts +0 -1
  90. package/providers/utils/syncDesiredState.d.ts +0 -12
  91. package/providers/utils/syncPlaybackState.d.ts +0 -4
  92. package/utils/StateMachine/StateMachine.d.ts +0 -17
  93. package/utils/StatefulIterator/index.d.ts +0 -13
  94. package/utils/ThroughputEstimator.d.ts +0 -25
  95. package/utils/addScript.d.ts +0 -2
  96. package/utils/autoSelectVideoTrack.d.ts +0 -24
  97. package/utils/buffer/getBufferedRangeForPosition.d.ts +0 -3
  98. package/utils/buffer/getForwardBufferDuration.d.ts +0 -3
  99. package/utils/hostnameFromUrl.d.ts +0 -2
  100. package/utils/iframeSafeStorage.d.ts +0 -5
  101. package/utils/isSafari.d.ts +0 -2
  102. package/utils/observeElementSize.d.ts +0 -3
  103. package/utils/playbackTelemetry.d.ts +0 -12
  104. package/utils/quality/types.d.ts +0 -21
  105. package/utils/quality/utils.d.ts +0 -20
  106. package/utils/smoothedValue.d.ts +0 -28
  107. package/utils/tuningConfig.d.ts +0 -75
  108. package/utils/videoFormat.d.ts +0 -2
package/es2015.cjs.js CHANGED
@@ -1,6 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.77
3
- * Thu, 19 Jan 2023 10:04:24 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-77/doc/
2
+ * @vkontakte/videoplayer-core v2.0.78
3
+ * Thu, 02 Feb 2023 10:14:35 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-78/doc/
5
5
  */
6
- 'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2015.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce.js'));var r,a,n,o,u,l;exports.PlaybackState=void 0,(r=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',r.PLAYING='playing',r.PAUSED='paused',exports.VideoFormat=void 0,(a=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',a.DASH='DASH',a.DASH_SEP='DASH_SEP',a.DASH_SEP_VK='DASH_SEP',a.DASH_WEBM='DASH_WEBM',a.DASH_WEBM_VK='DASH_WEBM',a.DASH_ONDEMAND='DASH_ONDEMAND',a.DASH_ONDEMAND_VK='DASH_ONDEMAND',a.DASH_LIVE='DASH_LIVE',a.DASH_LIVE_WEBM='DASH_LIVE_WEBM',a.HLS='HLS',a.HLS_ONDEMAND='HLS_ONDEMAND',a.HLS_JS='HLS',a.HLS_LIVE='HLS_LIVE',a.WEB_RTC_LIVE='WEB_RTC_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.HttpConnectionType=void 0,(u=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',u.HTTP2='http2',u.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(l||(l={}));class d{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;const r=t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast),a=Boolean(window.__onGCastApiAvailable);var n;r?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},a||(n='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',n),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',category:t.ErrorCategory.NETWORK,message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,r;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(r=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===r?void 0:r.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(c),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{var a;const n=r===exports.ChromecastState.CONNECTED,o=t.isNonNullable(this.connection$.getValue());if(n&&!o){const r=s.getCurrentSession();t.assertNonNullable(r);const n=r.getCastDevice(),o=null===(a=r.getMediaSession())||void 0===a?void 0:a.media.contentId;(t.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:r,castDevice:n}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)})))}initializeCastApi(){var e;let i,s,r;try{i=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{i.setOptions({receiverApplicationId:null!==(e=this.params.receiverApplicationId)&&void 0!==e?e:s,autoJoinPolicy:r}),this.initListeners()}catch(e){this.errorEvent$.next({id:'ChromecastInitializer',category:t.ErrorCategory.EXTERNAL_API,message:'[initializeCastApi] failed',thrown:e})}}}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 h='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},p=function(t){try{return!!t()}catch(t){return!0}},m=!p((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),f=m,v=Function.prototype,b=v.bind,S=v.call,g=f&&b.bind(S,S),y=f?function(t){return t&&g(t)}:function(t){return t&&function(){return S.apply(t,arguments)}},T=y,E=T({}.toString),k=T(''.slice),w=function(t){return k(E(t),8,-1)},P=p,$=w,A=Object,x=y(''.split),N=P((function(){return!A('z').propertyIsEnumerable(0)}))?function(t){return'String'==$(t)?x(t,''):A(t)}:A,R=TypeError,D=function(t){if(null==t)throw R('Can\'t call method on '+t);return t},C=N,_=D,I=function(t){return C(_(t))},L={},O=function(t){return t&&t.Math==Math&&t},B=O('object'==typeof globalThis&&globalThis)||O('object'==typeof window&&window)||O('object'==typeof self&&self)||O('object'==typeof h&&h)||function(){return this}()||Function('return this')(),M=function(t){return'function'==typeof t},V=B,F=Object.defineProperty,U=function(t,e){try{F(V,t,{value:e,configurable:!0,writable:!0})}catch(i){V[t]=e}return e},j=B['__core-js_shared__']||U('__core-js_shared__',{}),q=M,H=j,G=y(Function.toString);q(H.inspectSource)||(H.inspectSource=function(t){return G(t)});var Y,Q,z=H.inspectSource,W=M,J=z,K=B.WeakMap,X=W(K)&&/native code/.test(J(K)),Z=M,tt=function(t){return'object'==typeof t?null!==t:Z(t)},et=!p((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),it={},st=tt,rt=B.document,at=st(rt)&&st(rt.createElement),nt=function(t){return at?rt.createElement(t):{}},ot=nt,ut=!et&&!p((function(){return 7!=Object.defineProperty(ot('div'),'a',{get:function(){return 7}}).a})),lt=et&&p((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),dt=tt,ct=String,ht=TypeError,pt=function(t){if(dt(t))return t;throw ht(ct(t)+' is not an object')},mt=m,ft=Function.prototype.call,vt=mt?ft.bind(ft):function(){return ft.apply(ft,arguments)},bt={},St=bt,gt=B,yt=M,Tt=function(t){return yt(t)?t:void 0},Et=function(t,e){return arguments.length<2?Tt(St[t])||Tt(gt[t]):St[t]&&St[t][e]||gt[t]&&gt[t][e]},kt=y({}.isPrototypeOf),wt=Et('navigator','userAgent')||'',Pt=B,$t=wt,At=Pt.process,xt=Pt.Deno,Nt=At&&At.versions||xt&&xt.version,Rt=Nt&&Nt.v8;Rt&&(Q=(Y=Rt.split('.'))[0]>0&&Y[0]<4?1:+(Y[0]+Y[1])),!Q&&$t&&(!(Y=$t.match(/Edge\/(\d+)/))||Y[1]>=74)&&(Y=$t.match(/Chrome\/(\d+)/))&&(Q=+Y[1]);var Dt=Q,Ct=Dt,_t=p,It=!!Object.getOwnPropertySymbols&&!_t((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Ct&&Ct<41})),Lt=It&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,Ot=Et,Bt=M,Mt=kt,Vt=Object,Ft=Lt?function(t){return'symbol'==typeof t}:function(t){var e=Ot('Symbol');return Bt(e)&&Mt(e.prototype,Vt(t))},Ut=String,jt=function(t){try{return Ut(t)}catch(t){return'Object'}},qt=M,Ht=jt,Gt=TypeError,Yt=function(t){if(qt(t))return t;throw Gt(Ht(t)+' is not a function')},Qt=Yt,zt=function(t,e){var i=t[e];return null==i?void 0:Qt(i)},Wt=vt,Jt=M,Kt=tt,Xt=TypeError,Zt={exports:{}},te=j;(Zt.exports=function(t,e){return te[t]||(te[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.24.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE',source:'https://github.com/zloirock/core-js'});var ee=D,ie=Object,se=function(t){return ie(ee(t))},re=se,ae=y({}.hasOwnProperty),ne=Object.hasOwn||function(t,e){return ae(re(t),e)},oe=y,ue=0,le=Math.random(),de=oe(1..toString),ce=function(t){return'Symbol('+(void 0===t?'':t)+')_'+de(++ue+le,36)},he=B,pe=Zt.exports,me=ne,fe=ce,ve=It,be=Lt,Se=pe('wks'),ge=he.Symbol,ye=ge&&ge.for,Te=be?ge:ge&&ge.withoutSetter||fe,Ee=function(t){if(!me(Se,t)||!ve&&'string'!=typeof Se[t]){var e='Symbol.'+t;ve&&me(ge,t)?Se[t]=ge[t]:Se[t]=be&&ye?ye(e):Te(e)}return Se[t]},ke=vt,we=tt,Pe=Ft,$e=zt,Ae=function(t,e){var i,s;if('string'===e&&Jt(i=t.toString)&&!Kt(s=Wt(i,t)))return s;if(Jt(i=t.valueOf)&&!Kt(s=Wt(i,t)))return s;if('string'!==e&&Jt(i=t.toString)&&!Kt(s=Wt(i,t)))return s;throw Xt('Can\'t convert object to primitive value')},xe=TypeError,Ne=Ee('toPrimitive'),Re=function(t,e){if(!we(t)||Pe(t))return t;var i,s=$e(t,Ne);if(s){if(void 0===e&&(e='default'),i=ke(s,t,e),!we(i)||Pe(i))return i;throw xe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),Ae(t,e)},De=Ft,Ce=function(t){var e=Re(t,'string');return De(e)?e:e+''},_e=et,Ie=ut,Le=lt,Oe=pt,Be=Ce,Me=TypeError,Ve=Object.defineProperty,Fe=Object.getOwnPropertyDescriptor;it.f=_e?Le?function(t,e,i){if(Oe(t),e=Be(e),Oe(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Fe(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 Ve(t,e,i)}:Ve:function(t,e,i){if(Oe(t),e=Be(e),Oe(i),Ie)try{return Ve(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Me('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Ue,je,qe,He=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},Ge=it,Ye=He,Qe=et?function(t,e,i){return Ge.f(t,e,Ye(1,i))}:function(t,e,i){return t[e]=i,t},ze=Zt.exports,We=ce,Je=ze('keys'),Ke=function(t){return Je[t]||(Je[t]=We(t))},Xe={},Ze=X,ti=B,ei=y,ii=tt,si=Qe,ri=ne,ai=j,ni=Ke,oi=Xe,ui=ti.TypeError,li=ti.WeakMap;if(Ze||ai.state){var di=ai.state||(ai.state=new li),ci=ei(di.get),hi=ei(di.has),pi=ei(di.set);Ue=function(t,e){if(hi(di,t))throw new ui('Object already initialized');return e.facade=t,pi(di,t,e),e},je=function(t){return ci(di,t)||{}},qe=function(t){return hi(di,t)}}else{var mi=ni('state');oi[mi]=!0,Ue=function(t,e){if(ri(t,mi))throw new ui('Object already initialized');return e.facade=t,si(t,mi,e),e},je=function(t){return ri(t,mi)?t[mi]:{}},qe=function(t){return ri(t,mi)}}var fi={set:Ue,get:je,has:qe,enforce:function(t){return qe(t)?je(t):Ue(t,{})},getterFor:function(t){return function(e){var i;if(!ii(e)||(i=je(e)).type!==t)throw ui('Incompatible receiver, '+t+' required');return i}}},vi=m,bi=Function.prototype,Si=bi.apply,gi=bi.call,yi='object'==typeof Reflect&&Reflect.apply||(vi?gi.bind(Si):function(){return gi.apply(Si,arguments)}),Ti={},Ei={},ki={}.propertyIsEnumerable,wi=Object.getOwnPropertyDescriptor,Pi=wi&&!ki.call({1:2},1);Ei.f=Pi?function(t){var e=wi(this,t);return!!e&&e.enumerable}:ki;var $i=et,Ai=vt,xi=Ei,Ni=He,Ri=I,Di=Ce,Ci=ne,_i=ut,Ii=Object.getOwnPropertyDescriptor;Ti.f=$i?Ii:function(t,e){if(t=Ri(t),e=Di(e),_i)try{return Ii(t,e)}catch(t){}if(Ci(t,e))return Ni(!Ai(xi.f,t,e),t[e])};var Li=p,Oi=M,Bi=/#|\.prototype\./,Mi=function(t,e){var i=Fi[Vi(t)];return i==ji||i!=Ui&&(Oi(e)?Li(e):!!e)},Vi=Mi.normalize=function(t){return String(t).replace(Bi,'.').toLowerCase()},Fi=Mi.data={},Ui=Mi.NATIVE='N',ji=Mi.POLYFILL='P',qi=Mi,Hi=Yt,Gi=m,Yi=y(y.bind),Qi=function(t,e){return Hi(t),void 0===e?t:Gi?Yi(t,e):function(){return t.apply(e,arguments)}},zi=B,Wi=yi,Ji=y,Ki=M,Xi=Ti.f,Zi=qi,ts=bt,es=Qi,is=Qe,ss=ne,rs=function(t){var e=function(i,s,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,r)}return Wi(t,this,arguments)};return e.prototype=t.prototype,e},as=function(t,e){var i,s,r,a,n,o,u,l,d=t.target,c=t.global,h=t.stat,p=t.proto,m=c?zi:h?zi[d]:(zi[d]||{}).prototype,f=c?ts:ts[d]||is(ts,d,{})[d],v=f.prototype;for(r in e)i=!Zi(c?r:d+(h?'.':'#')+r,t.forced)&&m&&ss(m,r),n=f[r],i&&(o=t.dontCallGetSet?(l=Xi(m,r))&&l.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(u=t.bind&&i?es(a,zi):t.wrap&&i?rs(a):p&&Ki(a)?Ji(a):a,(t.sham||a&&a.sham||n&&n.sham)&&is(u,'sham',!0),is(f,r,u),p&&(ss(ts,s=d+'Prototype')||is(ts,s,{}),is(ts[s],r,a),t.real&&v&&!v[r]&&is(v,r,a)))},ns=et,os=ne,us=Function.prototype,ls=ns&&Object.getOwnPropertyDescriptor,ds=os(us,'name'),cs={EXISTS:ds,PROPER:ds&&'something'===function(){}.name,CONFIGURABLE:ds&&(!ns||ns&&ls(us,'name').configurable)},hs={},ps=Math.ceil,ms=Math.floor,fs=Math.trunc||function(t){var e=+t;return(e>0?ms:ps)(e)},vs=function(t){var e=+t;return e!=e||0===e?0:fs(e)},bs=vs,Ss=Math.max,gs=Math.min,ys=vs,Ts=Math.min,Es=function(t){return t>0?Ts(ys(t),9007199254740991):0},ks=function(t){return Es(t.length)},ws=I,Ps=function(t,e){var i=bs(t);return i<0?Ss(i+e,0):gs(i,e)},$s=ks,As=function(t){return function(e,i,s){var r,a=ws(e),n=$s(a),o=Ps(s,n);if(t&&i!=i){for(;n>o;)if((r=a[o++])!=r)return!0}else for(;n>o;o++)if((t||o in a)&&a[o]===i)return t||o||0;return!t&&-1}},xs={includes:As(!0),indexOf:As(!1)},Ns=ne,Rs=I,Ds=xs.indexOf,Cs=Xe,_s=y([].push),Is=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Ls=function(t,e){var i,s=Rs(t),r=0,a=[];for(i in s)!Ns(Cs,i)&&Ns(s,i)&&_s(a,i);for(;e.length>r;)Ns(s,i=e[r++])&&(~Ds(a,i)||_s(a,i));return a},Os=Is,Bs=Object.keys||function(t){return Ls(t,Os)},Ms=et,Vs=lt,Fs=it,Us=pt,js=I,qs=Bs;hs.f=Ms&&!Vs?Object.defineProperties:function(t,e){Us(t);for(var i,s=js(e),r=qs(e),a=r.length,n=0;a>n;)Fs.f(t,i=r[n++],s[i]);return t};var Hs,Gs=Et('document','documentElement'),Ys=pt,Qs=hs,zs=Is,Ws=Xe,Js=Gs,Ks=nt,Xs=Ke('IE_PROTO'),Zs=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},ir=function(){try{Hs=new ActiveXObject('htmlfile')}catch(t){}var t,e;ir='undefined'!=typeof document?document.domain&&Hs?er(Hs):((e=Ks('iframe')).style.display='none',Js.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(tr('document.F=Object')),t.close(),t.F):er(Hs);for(var i=zs.length;i--;)delete ir.prototype[zs[i]];return ir()};Ws[Xs]=!0;var sr,rr,ar,nr=Object.create||function(t,e){var i;return null!==t?(Zs.prototype=Ys(t),i=new Zs,Zs.prototype=null,i[Xs]=t):i=ir(),void 0===e?i:Qs.f(i,e)},or=!p((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ur=ne,lr=M,dr=se,cr=or,hr=Ke('IE_PROTO'),pr=Object,mr=pr.prototype,fr=cr?pr.getPrototypeOf:function(t){var e=dr(t);if(ur(e,hr))return e[hr];var i=e.constructor;return lr(i)&&e instanceof i?i.prototype:e instanceof pr?mr:null},vr=Qe,br=function(t,e,i,s){return s&&s.enumerable?t[e]=i:vr(t,e,i),t},Sr=p,gr=M,yr=nr,Tr=fr,Er=br,kr=Ee('iterator'),wr=!1;[].keys&&('next'in(ar=[].keys())?(rr=Tr(Tr(ar)))!==Object.prototype&&(sr=rr):wr=!0);var Pr=null==sr||Sr((function(){var t={};return sr[kr].call(t)!==t}));gr((sr=Pr?{}:yr(sr))[kr])||Er(sr,kr,(function(){return this}));var $r={IteratorPrototype:sr,BUGGY_SAFARI_ITERATORS:wr},Ar={};Ar[Ee('toStringTag')]='z';var xr='[object z]'===String(Ar),Nr=xr,Rr=M,Dr=w,Cr=Ee('toStringTag'),_r=Object,Ir='Arguments'==Dr(function(){return arguments}()),Lr=Nr?Dr: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=_r(t),Cr))?i:Ir?Dr(e):'Object'==(s=Dr(e))&&Rr(e.callee)?'Arguments':s},Or=Lr,Br=xr?{}.toString:function(){return'[object '+Or(this)+']'},Mr=xr,Vr=it.f,Fr=Qe,Ur=ne,jr=Br,qr=Ee('toStringTag'),Hr=function(t,e,i,s){if(t){var r=i?t:t.prototype;Ur(r,qr)||Vr(r,qr,{configurable:!0,value:e}),s&&!Mr&&Fr(r,'toString',jr)}},Gr=$r.IteratorPrototype,Yr=nr,Qr=He,zr=Hr,Wr=L,Jr=function(){return this},Kr=(TypeError,y);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Kr(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Xr=as,Zr=vt,ta=function(t,e,i,s){var r=e+' Iterator';return t.prototype=Yr(Gr,{next:Qr(+!s,i)}),zr(t,r,!1,!0),Wr[r]=Jr,t},ea=fr,ia=Hr,sa=br,ra=L,aa=cs.PROPER,na=$r.BUGGY_SAFARI_ITERATORS,oa=Ee('iterator'),ua=function(){return this},la=I,da=L,ca=fi;it.f;var ha=function(t,e,i,s,r,a,n){ta(i,e,s);var o,u,l,d=function(t){if(t===r&&f)return f;if(!na&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},c=e+' Iterator',h=!1,p=t.prototype,m=p[oa]||p['@@iterator']||r&&p[r],f=!na&&m||d(r),v='Array'==e&&p.entries||m;if(v&&(o=ea(v.call(new t)))!==Object.prototype&&o.next&&(ia(o,c,!0,!0),ra[c]=ua),aa&&'values'==r&&m&&'values'!==m.name&&(h=!0,f=function(){return Zr(m,this)}),r)if(u={values:d('values'),keys:a?f:d('keys'),entries:d('entries')},n)for(l in u)(na||h||!(l in p))&&sa(p,l,u[l]);else Xr({target:e,proto:!0,forced:na||h},u);return n&&p[oa]!==f&&sa(p,oa,f,{name:r}),ra[e]=f,u},pa=ca.set,ma=ca.getterFor('Array Iterator');ha(Array,'Array',(function(t,e){pa(this,{type:'Array Iterator',target:la(t),index:0,kind:e})}),(function(){var t=ma(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'),da.Arguments=da.Array;var fa=L,va=Ee('iterator'),ba=Array.prototype,Sa=Lr,ga=zt,ya=L,Ta=Ee('iterator'),Ea=function(t){if(null!=t)return ga(t,Ta)||ga(t,'@@iterator')||ya[Sa(t)]},ka=vt,wa=Yt,Pa=pt,$a=jt,Aa=Ea,xa=TypeError,Na=vt,Ra=pt,Da=zt,Ca=Qi,_a=vt,Ia=pt,La=jt,Oa=function(t){return void 0!==t&&(fa.Array===t||ba[va]===t)},Ba=ks,Ma=kt,Va=function(t,e){var i=arguments.length<2?Aa(t):e;if(wa(i))return Pa(ka(i,t));throw xa($a(t)+' is not iterable')},Fa=Ea,Ua=function(t,e,i){var s,r;Ra(t);try{if(!(s=Da(t,'return'))){if('throw'===e)throw i;return i}s=Na(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return Ra(s),i},ja=TypeError,qa=function(t,e){this.stopped=t,this.result=e},Ha=qa.prototype,Ga=function(t,e,i){var s,r,a,n,o,u,l,d=i&&i.that,c=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=Ca(e,d),v=function(t){return s&&Ua(s,'normal',t),new qa(!0,t)},b=function(t){return c?(Ia(t),m?f(t[0],t[1],v):f(t[0],t[1])):m?f(t,v):f(t)};if(h)s=t.iterator;else if(p)s=t;else{if(!(r=Fa(t)))throw ja(La(t)+' is not iterable');if(Oa(r)){for(a=0,n=Ba(t);n>a;a++)if((o=b(t[a]))&&Ma(Ha,o))return o;return new qa(!1)}s=Va(t,r)}for(u=h?t.next:s.next;!(l=_a(u,s)).done;){try{o=b(l.value)}catch(t){Ua(s,'throw',t)}if('object'==typeof o&&o&&Ma(Ha,o))return o}return new qa(!1)},Ya=Ce,Qa=it,za=He,Wa=Ga,Ja=function(t,e,i){var s=Ya(e);s in t?Qa.f(t,s,za(0,i)):t[s]=i};as({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Wa(t,(function(t,i){Ja(e,t,i)}),{AS_ENTRIES:!0}),e}});var Ka=bt.Object.fromEntries,Xa={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},Za=B,tn=Lr,en=Qe,sn=L,rn=Ee('toStringTag');for(var an in Xa){var nn=Za[an],on=nn&&nn.prototype;on&&tn(on)!==rn&&en(on,rn,an),sn[an]=sn.Array}var un=Ka,ln='process'==w(B.process),dn=Et,cn=it,hn=et,pn=Ee('species'),mn=kt,fn=TypeError,vn=y,bn=p,Sn=M,gn=Lr,yn=z,Tn=function(){},En=[],kn=Et('Reflect','construct'),wn=/^\s*(?:class|function)\b/,Pn=vn(wn.exec),$n=!wn.exec(Tn),An=function(t){if(!Sn(t))return!1;try{return kn(Tn,En,t),!0}catch(t){return!1}},xn=function(t){if(!Sn(t))return!1;switch(gn(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return $n||!!Pn(wn,yn(t))}catch(t){return!0}};xn.sham=!0;var Nn,Rn,Dn,Cn,_n=!kn||bn((function(){var t;return An(An.call)||!An(Object)||!An((function(){t=!0}))||t}))?xn:An,In=jt,Ln=TypeError,On=pt,Bn=function(t){if(_n(t))return t;throw Ln(In(t)+' is not a constructor')},Mn=Ee('species'),Vn=function(t,e){var i,s=On(t).constructor;return void 0===s||null==(i=On(s)[Mn])?e:Bn(i)},Fn=y([].slice),Un=TypeError,jn=/(?:ipad|iphone|ipod).*applewebkit/i.test(wt),qn=B,Hn=yi,Gn=Qi,Yn=M,Qn=ne,zn=p,Wn=Gs,Jn=Fn,Kn=nt,Xn=function(t,e){if(t<e)throw Un('Not enough arguments');return t},Zn=jn,to=ln,eo=qn.setImmediate,io=qn.clearImmediate,so=qn.process,ro=qn.Dispatch,ao=qn.Function,no=qn.MessageChannel,oo=qn.String,uo=0,lo={};try{Nn=qn.location}catch(t){}var co=function(t){if(Qn(lo,t)){var e=lo[t];delete lo[t],e()}},ho=function(t){return function(){co(t)}},po=function(t){co(t.data)},mo=function(t){qn.postMessage(oo(t),Nn.protocol+'//'+Nn.host)};eo&&io||(eo=function(t){Xn(arguments.length,1);var e=Yn(t)?t:ao(t),i=Jn(arguments,1);return lo[++uo]=function(){Hn(e,void 0,i)},Rn(uo),uo},io=function(t){delete lo[t]},to?Rn=function(t){so.nextTick(ho(t))}:ro&&ro.now?Rn=function(t){ro.now(ho(t))}:no&&!Zn?(Cn=(Dn=new no).port2,Dn.port1.onmessage=po,Rn=Gn(Cn.postMessage,Cn)):qn.addEventListener&&Yn(qn.postMessage)&&!qn.importScripts&&Nn&&'file:'!==Nn.protocol&&!zn(mo)?(Rn=mo,qn.addEventListener('message',po,!1)):Rn='onreadystatechange'in Kn('script')?function(t){Wn.appendChild(Kn('script')).onreadystatechange=function(){Wn.removeChild(this),co(t)}}:function(t){setTimeout(ho(t),0)});var fo,vo,bo,So,go,yo,To,Eo,ko={set:eo,clear:io},wo=B,Po=/ipad|iphone|ipod/i.test(wt)&&void 0!==wo.Pebble,$o=/web0s(?!.*chrome)/i.test(wt),Ao=B,xo=Qi,No=Ti.f,Ro=ko.set,Do=jn,Co=Po,_o=$o,Io=ln,Lo=Ao.MutationObserver||Ao.WebKitMutationObserver,Oo=Ao.document,Bo=Ao.process,Mo=Ao.Promise,Vo=No(Ao,'queueMicrotask'),Fo=Vo&&Vo.value;Fo||(fo=function(){var t,e;for(Io&&(t=Bo.domain)&&t.exit();vo;){e=vo.fn,vo=vo.next;try{e()}catch(t){throw vo?So():bo=void 0,t}}bo=void 0,t&&t.enter()},Do||Io||_o||!Lo||!Oo?!Co&&Mo&&Mo.resolve?((To=Mo.resolve(void 0)).constructor=Mo,Eo=xo(To.then,To),So=function(){Eo(fo)}):Io?So=function(){Bo.nextTick(fo)}:(Ro=xo(Ro,Ao),So=function(){Ro(fo)}):(go=!0,yo=Oo.createTextNode(''),new Lo(fo).observe(yo,{characterData:!0}),So=function(){yo.data=go=!go}));var Uo=Fo||function(t){var e={fn:t,next:void 0};bo&&(bo.next=e),vo||(vo=e,So()),bo=e},jo=B,qo=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},Ho=function(){this.head=null,this.tail=null};Ho.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}};var Go=Ho,Yo=B.Promise,Qo='object'==typeof Deno&&Deno&&'object'==typeof Deno.version,zo=!Qo&&!ln&&'object'==typeof window&&'object'==typeof document,Wo=B,Jo=Yo,Ko=M,Xo=qi,Zo=z,tu=Ee,eu=zo,iu=Qo,su=Dt,ru=Jo&&Jo.prototype,au=tu('species'),nu=!1,ou=Ko(Wo.PromiseRejectionEvent),uu={CONSTRUCTOR:Xo('Promise',(function(){var t=Zo(Jo),e=t!==String(Jo);if(!e&&66===su)return!0;if(!ru.catch||!ru.finally)return!0;if(!su||su<51||!/native code/.test(t)){var i=new Jo((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};if((i.constructor={})[au]=s,!(nu=i.then((function(){}))instanceof s))return!0}return!e&&(eu||iu)&&!ou})),REJECTION_EVENT:ou,SUBCLASSING:nu},lu={},du=Yt,cu=function(t){var e,i;this.promise=new t((function(t,s){if(void 0!==e||void 0!==i)throw TypeError('Bad Promise constructor');e=t,i=s})),this.resolve=du(e),this.reject=du(i)};lu.f=function(t){return new cu(t)};var hu,pu,mu=as,fu=ln,vu=B,bu=vt,Su=br,gu=Hr,yu=function(t){var e=dn(t),i=cn.f;hn&&e&&!e[pn]&&i(e,pn,{configurable:!0,get:function(){return this}})},Tu=Yt,Eu=M,ku=tt,wu=function(t,e){if(mn(e,t))return t;throw fn('Incorrect invocation')},Pu=Vn,$u=ko.set,Au=Uo,xu=function(t,e){var i=jo.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},Nu=qo,Ru=Go,Du=fi,Cu=Yo,_u=lu,Iu=uu.CONSTRUCTOR,Lu=uu.REJECTION_EVENT,Ou=Du.getterFor('Promise'),Bu=Du.set,Mu=Cu&&Cu.prototype,Vu=Cu,Fu=Mu,Uu=vu.TypeError,ju=vu.document,qu=vu.process,Hu=_u.f,Gu=Hu,Yu=!!(ju&&ju.createEvent&&vu.dispatchEvent),Qu=function(t){var e;return!(!ku(t)||!Eu(e=t.then))&&e},zu=function(t,e){var i,s,r,a=e.value,n=1==e.state,o=n?t.ok:t.fail,u=t.resolve,l=t.reject,d=t.domain;try{o?(n||(2===e.rejection&&Zu(e),e.rejection=1),!0===o?i=a:(d&&d.enter(),i=o(a),d&&(d.exit(),r=!0)),i===t.promise?l(Uu('Promise-chain cycle')):(s=Qu(i))?bu(s,i,u,l):u(i)):l(a)}catch(t){d&&!r&&d.exit(),l(t)}},Wu=function(t,e){t.notified||(t.notified=!0,Au((function(){for(var i,s=t.reactions;i=s.get();)zu(i,t);t.notified=!1,e&&!t.rejection&&Ku(t)})))},Ju=function(t,e,i){var s,r;Yu?((s=ju.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),vu.dispatchEvent(s)):s={promise:e,reason:i},!Lu&&(r=vu['on'+t])?r(s):'unhandledrejection'===t&&xu('Unhandled promise rejection',i)},Ku=function(t){bu($u,vu,(function(){var e,i=t.facade,s=t.value;if(Xu(t)&&(e=Nu((function(){fu?qu.emit('unhandledRejection',s,i):Ju('unhandledrejection',i,s)})),t.rejection=fu||Xu(t)?2:1,e.error))throw e.value}))},Xu=function(t){return 1!==t.rejection&&!t.parent},Zu=function(t){bu($u,vu,(function(){var e=t.facade;fu?qu.emit('rejectionHandled',e):Ju('rejectionhandled',e,t.value)}))},tl=function(t,e,i){return function(s){t(e,s,i)}},el=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,Wu(t,!0))},il=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw Uu('Promise can\'t be resolved itself');var s=Qu(e);s?Au((function(){var i={done:!1};try{bu(s,e,tl(il,i,t),tl(el,i,t))}catch(e){el(i,e,t)}})):(t.value=e,t.state=1,Wu(t,!1))}catch(e){el({done:!1},e,t)}}};Iu&&(Fu=(Vu=function(t){wu(this,Fu),Tu(t),bu(hu,this);var e=Ou(this);try{t(tl(il,e),tl(el,e))}catch(t){el(e,t)}}).prototype,(hu=function(t){Bu(this,{type:'Promise',done:!1,notified:!1,parent:!1,reactions:new Ru,rejection:!1,state:0,value:void 0})}).prototype=Su(Fu,'then',(function(t,e){var i=Ou(this),s=Hu(Pu(this,Vu));return i.parent=!0,s.ok=!Eu(t)||t,s.fail=Eu(e)&&e,s.domain=fu?qu.domain:void 0,0==i.state?i.reactions.add(s):Au((function(){zu(s,i)})),s.promise})),pu=function(){var t=new hu,e=Ou(t);this.promise=t,this.resolve=tl(il,e),this.reject=tl(el,e)},_u.f=Hu=function(t){return t===Vu||undefined===t?new pu(t):Gu(t)}),mu({global:!0,constructor:!0,wrap:!0,forced:Iu},{Promise:Vu}),gu(Vu,'Promise',!1,!0),yu('Promise');var sl=Ee('iterator'),rl=!1;try{var al=0,nl={next:function(){return{done:!!al++}},return:function(){rl=!0}};nl[sl]=function(){return this},Array.from(nl,(function(){throw 2}))}catch(t){}var ol=Yo,ul=uu.CONSTRUCTOR||!function(t,e){if(!e&&!rl)return!1;var i=!1;try{var s={};s[sl]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i}((function(t){ol.all(t).then(void 0,(function(){}))})),ll=vt,dl=Yt,cl=lu,hl=qo,pl=Ga;as({target:'Promise',stat:!0,forced:ul},{all:function(t){var e=this,i=cl.f(e),s=i.resolve,r=i.reject,a=hl((function(){var i=dl(e.resolve),a=[],n=0,o=1;pl(t,(function(t){var u=n++,l=!1;o++,ll(i,e,t).then((function(t){l||(l=!0,a[u]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise}});var ml=as,fl=uu.CONSTRUCTOR;Yo&&Yo.prototype,ml({target:'Promise',proto:!0,forced:fl,real:!0},{catch:function(t){return this.then(void 0,t)}});var vl=vt,bl=Yt,Sl=lu,gl=qo,yl=Ga;as({target:'Promise',stat:!0,forced:ul},{race:function(t){var e=this,i=Sl.f(e),s=i.reject,r=gl((function(){var r=bl(e.resolve);yl(t,(function(t){vl(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var Tl=vt,El=lu;as({target:'Promise',stat:!0,forced:uu.CONSTRUCTOR},{reject:function(t){var e=El.f(this);return Tl(e.reject,void 0,t),e.promise}});var kl=pt,wl=tt,Pl=lu,$l=function(t,e){if(kl(t),wl(e)&&e.constructor===t)return e;var i=Pl.f(t);return(0,i.resolve)(e),i.promise},Al=as,xl=Yo,Nl=uu.CONSTRUCTOR,Rl=$l,Dl=Et('Promise'),Cl=!Nl;Al({target:'Promise',stat:!0,forced:true},{resolve:function(t){return Rl(Cl&&this===Dl?xl:this,t)}});var _l=as,Il=Yo,Ll=p,Ol=Et,Bl=M,Ml=Vn,Vl=$l,Fl=Il&&Il.prototype;_l({target:'Promise',proto:!0,real:!0,forced:!!Il&&Ll((function(){Fl.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=Ml(this,Ol('Promise')),i=Bl(t);return this.then(i?function(i){return Vl(e,t()).then((function(){return i}))}:t,i?function(i){return Vl(e,t()).then((function(){throw i}))}:t)}});var Ul,jl=Et,ql=jl('Promise','finally');!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Ul||(Ul={}));var Hl,Gl=(e,i=0,s=Ul.OFFSET_P)=>{switch(s){case Ul.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case Ul.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},Yl=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(Hl=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',Hl.Q_144P='144p',Hl.Q_240P='240p',Hl.Q_360P='360p',Hl.Q_480P='480p',Hl.Q_720P='720p',Hl.Q_1080P='1080p',Hl.Q_1440P='1440p',Hl.Q_2160P='2160p',Hl.Q_4320P='4320p';const Ql={[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}},zl=(t,e)=>Ql[t].height>Ql[e].height,Wl=(t,e)=>Ql[t].height<Ql[e].height,Jl=Object.keys(Ql).sort(((t,e)=>Wl(t,e)?-1:1)),Kl=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return Jl.find((t=>{const e=Ql[t];return e.width>=s&&e.height>=i}))},Xl=t=>t===exports.VideoQuality.INVARIANT;class Zl{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 td;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(td||(td={}));class ed{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new Zl(td.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==r?void 0:r.to)===exports.PlaybackState.PAUSED||a.state!==l.Requested||e===td.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case td.PLAYING:break;case td.PAUSED:case td.READY:this.videoState.startTransitionTo(td.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case td.STOPPED:this.videoState.startTransitionTo(td.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case td.PLAYING:this.videoState.startTransitionTo(td.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case td.PAUSED:break;case td.READY:this.videoState.startTransitionTo(td.PAUSED),this.videoState.setState(td.PAUSED);break;case td.STOPPED:this.videoState.startTransitionTo(td.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(a.position)}else e!==td.STOPPED&&(this.videoState.startTransitionTo(td.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_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===l.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,r=this.params.output.isBuffering$.getValue(),a=s===chrome.cast.media.PlayerState.BUFFERING;switch(r!==a&&this.params.output.isBuffering$.next(a),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),Yl(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(td.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(td.PLAYING),Yl(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)!==td.PAUSED&&t!==td.PLAYING||(this.videoState.setState(td.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==td.PLAYING&&t!==td.PAUSED||(this.videoState.setState(td.PLAYING),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===td.READY&&this.videoState.setState(td.READY)}handleRemoteStop(){this.videoState.getState()!==td.STOPPED&&this.videoState.setState(td.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(e){var i;const s=this.params.source;let r,a,n;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const o=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:Wl(t,e)?1:-1))[0];t.assertNonNullable(o);const u=i[o];t.assertNonNullable(u),r=u,a='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),r=Gl(i.url),a='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const e='Unsupported format for Chromecast',i=new Error(e);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',category:t.ErrorCategory.VIDEO_PIPELINE,message:e,thrown:i}),i}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}const o=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:l}=this.params.meta;return t.isNonNullable(u)&&(o.metadata.title=u),t.isNonNullable(l)&&(o.metadata.subtitle=l),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)'))))}));ql(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()}),(e=>{const i=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:i}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',category:t.ErrorCategory.VIDEO_PIPELINE,message:i,thrown:e})})),(()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}function id(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{u(s.next(t))}catch(t){a(t)}}function o(t){try{u(s.throw(t))}catch(t){a(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}u((s=s.apply(t,e||[])).next())}))}function sd(t){return this instanceof sd?(this.v=t,this):new sd(t)}function rd(t,e,i){if(!Symbol.asyncIterator)throw new TypeError('Symbol.asyncIterator is not defined.');var s,r=i.apply(t,e||[]),a=[];return s={},n('next'),n('throw'),n('return'),s[Symbol.asyncIterator]=function(){return this},s;function n(t){r[t]&&(s[t]=function(e){return new Promise((function(i,s){a.push([t,e,i,s])>1||o(t,e)}))})}function o(t,e){try{(i=r[t](e)).value instanceof sd?Promise.resolve(i.value.v).then(u,l):d(a[0][2],i)}catch(t){d(a[0][3],t)}var i}function u(t){o('next',t)}function l(t){o('throw',t)}function d(t,e){t(e),a.shift(),a.length&&o(a[0][0],a[0][1])}}class ad{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 nd extends ad{constructor(){super(),this.listeners||ad.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 od{constructor(){Object.defineProperty(this,'signal',{value:new nd,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 ud(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&&(od.prototype[Symbol.toStringTag]='AbortController',nd.prototype[Symbol.toStringTag]='AbortSignal');const ld=ud({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dd=ld?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!ud({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty('signal')||r)&&(a=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const r=new i(t,e);return s&&Object.defineProperty(r,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),r},a.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=a&&a.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const r=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,n(t,e)])}return n(t,e)},Request:a}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,cd=ld?dd.fetch:window.fetch;ld?dd.Request:window.Request;const hd=ld?od:window.AbortController,pd=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class md{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}executeNextRequests(){return id(this,void 0,void 0,(function*(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[r,a]=pd(s.request);if(r>=i.from&&a<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}))}abort(t){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),r=this.activeRequests.get(i.url);s&&r&&r.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,i){const s=i.map(pd),r=s[0][0];let a=s[0][1];for(let t=1;t<s.length&&a<this.params.minDataSize;t++){const e=s[t][1];e-r<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===r?Math.max(a,r+this.params.minInitSize):Math.max(a,r+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append('bytes',`${r}-${a}`);const o=n.toString(),u=new hd,l=u.signal,d={url:e,from:r,to:a,loaded:0,data:null,abortController:u};l.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const c=e=>{var i,s;throw null===(s=(i=this.params).onError)||void 0===s||s.call(i,{id:'BigRequestParsing',category:t.ErrorCategory.PARSER,message:'Error parsing response data',thrown:e}),e};return cd(o,{signal:l}).then((t=>{var e,i,s;if(d.response=t,!t.ok||!t.body)return void this.onBigRequestError(d);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const u=n.getReader(),l=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10)||a-r+1;d.data=new ArrayBuffer(l);const h=new Uint8Array(d.data),p=({done:t,value:e})=>id(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(d):e&&(h.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),yield null==u?void 0:u.read().then(p,md.suppressStreamErrors).catch(c))}));null==u||u.read().then(p,md.suppressStreamErrors).catch(c)}),md.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,u,l,d,c,h,p;if(!this.activeRequests.has(t)||!r)return;const m=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of m){const{request:m}=n,[f,v]=pd(m),b=f>=e&&v<=e+s,S=e>=f&&e+s<v,g=r.slice(f-e,Math.min(v-e+1,s));if((b||S)&&(m.requestStartDate=null!==(o=m.requestStartDate)&&void 0!==o?o:new Date,m.firstByteDate=null!==(u=m.firstByteDate)&&void 0!==u?u:new Date,m.bytesLoaded=g.byteLength,m.bytesTotal=i-e),b){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(l=this.dashJsRequestQueue.get(t))&&void 0!==l?l:[]).filter((t=>t!==n))),null===(d=n.success)||void 0===d||d.call(n,g,'',t);const e=a?Array.from(a.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(c=this.dashMetrics)||void 0===c||c.addHttpRequest(m,t,null!==(h=null==a?void 0:a.status)&&void 0!==h?h:200,e,[])}else S&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:i,to:s},r){var a,n,o,u;if(null===(n=(a=this.params).onError)||void 0===n||n.call(a,{id:'BigRequest',category:t.ErrorCategory.NETWORK,message:'Download error',thrown:r}),!this.activeRequests.has(e))return;const l=null!==(o=this.dashJsRequestQueue.get(e))&&void 0!==o?o:[];for(const t of l){const[e,a]=pd(t.request);(e>=i&&e<s||a>i&&a<=s)&&(null===(u=null==t?void 0:t.error)||void 0===u||u.call(t,t.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=pd(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.call(t,t.request))}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class fd{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(fd.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;fd.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const vd=(t,e)=>{const i=new md(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new fd(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var bd=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},Sd=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject,r=new t.ValueSubject(void 0),a=new t.ValueSubject(void 0);let n=NaN,o=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,u=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const u=e.onload,l=e.progress;e.onload=function(...e){return(e=>{var s,n,o,u,l;const d=un(e.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in d||'x-playback-duration-millis'in d){const r=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),a=parseInt(null!==(n=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==n?n:'',10),u=null!==(o=null!=a?a:1e3*r)&&void 0!==o?o:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)}const c=null!==(u=d['x-delivery-type'])&&void 0!==u?u:exports.HttpConnectionType.HTTP1,h=null!==(l={1:!0,0:!1}[d['x-reused']])&&void 0!==l?l:void 0;r.next(c),a.next(h)})(this),u(...e)},e.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,s.next(Date.now()-n)),l(...t)},n=Date.now(),o=!1}return u(e)}}}),!0),{playbackDuration$:i,ping$:s,connectionReused$:a,connectionType$:r}},gd=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},yd=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 Td=(e,i,s,{equal:r=((t,e)=>t===e),changed$:a,onError:n}={})=>{const o=e.getState(),u=i(),l=t.isNullable(a),d=new t.Subscription;return a&&d.add(a.subscribe((t=>{const i=e.getState();r(t,i)&&e.setState(t)}),n)),r(u,o)||(s(o),l&&e.setState(o)),d.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),l&&e.setState(t.to)}),n)),d},Ed=(e,i,s)=>Td(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),kd=(e,i,s,r)=>Td(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:s,onError:r}),wd=(e,i,s,r)=>Td(i,(()=>e.playbackRate),(i=>{t.isNonNullable(i)&&(e.playbackRate=i)}),{changed$:s,onError:r}),Pd=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class $d{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const r=e=>{this.error$.next({id:'TextTracksManager',category:t.ErrorCategory.WTF,message:'Generic HtmlVideoTextTrackManager error',thrown:e})};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(Td(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(Td(i.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add(Td(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter($d.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)&&Pd(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 Ad=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),e.setAttribute('poster','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='),t.appendChild(e),e};class xd{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 Nd=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class Rd{constructor(t){this._buffer=[],this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:r})=>{const a=s>=t&&s<e,n=r>=t&&r<e;a&&n||(a?i(e,r):n?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var Dd=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const n=t.start(a),o=t.end(a);if(n<=e&&e<=o){if(s=n,r=o,!i)return{from:s,to:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{from:s,to:r}};const Cd=e=>{const i=i=>t.fromEvent(e,i).pipe(t.mapTo(void 0)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((t=>'ended'===t.type?e.readyState<2:e.readyState<3)),t.filterChanged()),r=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>Dd(e.buffered,e.currentTime)))),a=Nd()?t.combine({play:i('play').pipe(t.once()),playing:i('playing')}).pipe(t.mapTo(void 0)):i('playing'),n=t.fromEvent(e,'volumechange').pipe(t.map((()=>({muted:e.muted,volume:e.volume})))),o=t.fromEvent(e,'ratechange').pipe(t.map((()=>e.playbackRate))),u=t.fromEvent(e,'error').pipe(t.filter((()=>Boolean(e.error||e.played.length))),t.map((()=>{var i;const s=e.error;return{id:s?`MediaError#${s.code}`:'HtmlVideoError',category:t.ErrorCategory.VIDEO_PIPELINE,message:s?s.message:'Error event from HTML video element',thrown:null!==(i=e.error)&&void 0!==i?i:void 0}}))),l=t.fromEvent(e,'timeupdate').pipe(t.map((()=>e.currentTime))),d=new t.Subject;let c;return l.subscribe((i=>{e.loop&&t.isNonNullable(c)&&t.isNonNullable(i)&&c>=e.duration-.3&&i<=.3&&d.next(c),c=i})),{playing$:a,pause$:i('pause').pipe(t.filter((()=>!e.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:d,error$:u,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:t.fromEvent(e,'durationchange').pipe(t.map((()=>e.duration))),isBuffering$:s,currentBuffer$:r,volumeState$:n,playbackRateState$:o}},_d=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var Id=se,Ld=ks,Od=vs;as({target:'Array',proto:!0},{at:function(t){var e=Id(this),i=Ld(e),s=Od(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var Bd=jl('Array','at');let Md=!1,Vd={};const Fd=t=>{t(Vd)},Ud=(t,e)=>{var i;Md&&(Vd.meta=null!==(i=Vd.meta)&&void 0!==i?i:{},Vd.meta[t]=e)};class jd{constructor(t){this.name=t}next(t){var e,i;if(!Md)return;Vd.series=null!==(e=Vd.series)&&void 0!==e?e:{};const s=null!==(i=Vd.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Vd.series[this.name]=s}}const qd=new jd('best_bitrate');class Hd{constructor(){this.history={}}recordSelection(e){this.history[e.id]=t.now()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Gd=(e,{container:i,throughput:s,tuning:r,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:l,history:d})=>{var c,h,p,m;const f=r.usePixelRatio&&null!==(c=window.devicePixelRatio)&&void 0!==c?c:1,v=r.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*f*r.containerSizeFactor,height:i.height*f*r.containerSizeFactor},b=v&&Kl(v),S=r.considerPlaybackRate&&t.isNonNullable(u)?u:1,g=e.filter((t=>!Xl(t.quality))).sort(((t,e)=>zl(t.quality,e.quality)?-1:1)),y=null===(h=Bd(g,-1))||void 0===h?void 0:h.quality,T=null===(p=Bd(g,0))||void 0===p?void 0:p.quality,E=t.isNullable(a)||t.isNonNullable(a.min)&&t.isNonNullable(a.max)&&Wl(a.max,a.min)||t.isNonNullable(a.min)&&T&&zl(a.min,T)||t.isNonNullable(a.max)&&y&&Wl(a.max,y),k=S*(w=null!=o?o:.5,P=r.bitrateFactorAtEmptyBuffer,$=r.bitrateFactorAtFullBuffer,(P-$)*Math.pow(2,-10*w)+$);var w,P,$;const A=g.filter((e=>{const i=!b||Wl(e.quality,b),u=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s-n>=e.bitrate*k,d=r.lazyQualitySwitch&&t.isNonNullable(r.minBufferToSwitchUp)&&l&&!Xl(l.quality)&&(null!=o?o:0)<r.minBufferToSwitchUp&&zl(e.quality,l.quality),c=E||(t.isNullable(a.max)||(h=e.quality,p=a.max,Ql[h].height<=Ql[p].height))&&(t.isNullable(a.min)||((t,e)=>Ql[t].height>=Ql[e].height)(e.quality,a.min));var h,p;return i&&u&&!d&&c}))[0];A&&A.bitrate&&qd.next(A.bitrate);const x=null!==(m=null!=A?A:g[Math.ceil((g.length-1)/2)])&&void 0!==m?m:e[0],N=x&&d&&d.history[x.id]&&t.now()-d.history[x.id]<=r.trackCooldown&&(!d.last||x.id!==d.last.id);if((null==x?void 0:x.id)&&d&&!N&&d.recordSelection(x),N&&(null==d?void 0:d.last)){const t=d.last;return null==d||d.recordSwitch(t),t}return null==d||d.recordSwitch(x),x};var Yd=t=>new URL(t).hostname;const Qd=(e,i=300)=>new t.Observable((r=>{const{width:a,height:n}=e.getBoundingClientRect();if(r.next({width:a,height:n}),!window.ResizeObserver)return;const o=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,a;i.contentBoxSize&&i.contentBoxSize[0]?(a=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,a=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(a)&&r.next({width:s,height:a})}),i));return o.observe(e),()=>o.disconnect()})),zd={};var Wd;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Wd||(Wd={}));const Jd=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class Kd{constructor(e){this.subscription=new t.Subscription,this.videoState=new Zl(Wd.DOWNLOADING_LIB),this.textTracksManager=new $d,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 xd,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==Wd.DOWNLOADING_LIB&&e!==Wd.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&e!==Wd.STOPPED&&i!==exports.PlaybackState.STOPPED&&(a?this.seek(r.position-this.liveOffset.getTotalPausedTime()):this.seek(r.position)),i){case exports.PlaybackState.STOPPED:switch(e){case Wd.STOPPED:break;case Wd.PLAYING:case Wd.PAUSED:case Wd.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Wd.PLAYING:break;case Wd.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Wd.READY:this.play();break;case Wd.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Wd.PLAYING:this.pause(),this.liveOffset.pause();break;case Wd.PAUSED:break;case Wd.READY:this.videoState.setState(Wd.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Wd.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Ad(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Yd(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const s=i=>{var s;e||this.params.output.error$.next({id:'timeout'===i?'DashJSTimedOut':'DashJSLoadingError',category:t.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${null===(s=null==i?void 0:i.toString)||void 0===s?void 0:s.call(i)}`,thrown:i}),e=!0},r=window.setTimeout((()=>s('timeout')),5e3);ql(Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((t=>{e||(zd.MediaPlayer=t.MediaPlayer,zd.Debug=t.Debug,this.init())}),s),(()=>{window.clearTimeout(r),e=!0}))}init(){t.assertNonNullable(zd.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(zd.Debug,'dashjs not loaded'),this.player=zd.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?_d(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=vd(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&&yd(this.player),bd(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:gd})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Wd.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'DashIFProvider',category:t.ErrorCategory.WTF,message:'DashIFProvider internal logic error',thrown:i})},r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(Qd(this.video),this.elementSize$),r(Jd(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),r(Jd(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const a=Jd(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));a.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===Wd.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(Td(i.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:a.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(Td(i.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:s})),r(Jd(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),r(Jd(this.player,'fragmentLoadingStarted'),(({mediaType:t,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(t,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(t,'X-Delivery-Type'))&&void 0!==s?s:exports.HttpConnectionType.HTTP1,u=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(u),e.hostname$.next(Yd(i))})),r(Jd(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),this.videoTracks=[];const r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=Kl(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===r&&(a=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&e.currentVideoTrack$.next(a),this.videoState.setState(Wd.STREAM_INITIALIZED),this.videoState.startTransitionTo(Wd.READY)})),r(Jd(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),r(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=Gd(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),r(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const n=Jd(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));r(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:n}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(n.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),r(Jd(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),r(Jd(this.player,'playbackEnded'),e.endedEvent$),r(Jd(this.player,'playbackProgress').pipe(t.map((()=>Dd(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),r(Jd(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Wd.PLAYING),Yl(i.playbackState,exports.PlaybackState.PLAYING)})),r(Jd(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Wd.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(Jd(this.player,'playbackPaused'),(()=>{this.videoState.setState(Wd.PAUSED),Yl(i.playbackState,exports.PlaybackState.PAUSED)})),r(Jd(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Wd.READY&&this.videoState.setState(Wd.READY)})),r(this.isLive$,e.isLive$),r(Qd(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:o,ping$:u,connectionType$:l,connectionReused$:d}=Sd(this.player);r(l,this.params.output.httpConnectionType$),r(d,this.params.output.httpConnectionReused$),r(o,this.maxSeekBackTime$),r(u.pipe(t.once()),e.firstBytesEvent$),r(Jd(this.player,'canPlay'),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),r(n.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(Jd(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{this.subscription.add(Jd(this.player,'playbackPlaying').pipe(t.once(),t.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))}),s)),this.subscription.add(Ed(this.video,i.isLooped,s));const{volumeState$:c,looped$:h,playbackRateState$:p}=Cd(this.video);this.subscription.add(kd(this.video,i.volume,c,s)),this.subscription.add(c.subscribe(e.volume$,s)),this.subscription.add(h.subscribe(e.loopedEvent$)),this.subscription.add(wd(this.video,i.playbackRate,p,s))}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(Wd.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Wd.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=Gl(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ul.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Wd.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Wd.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 Xd=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}},Zd=t=>id(void 0,void 0,void 0,(function*(){const e=t.muted;try{yield t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{yield t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0}));function tc(){return t.now()}function ec(t){return tc()-t}function ic(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function sc(e,i,s,r){const a=window.XMLHttpRequest;let n,o,u,l,d,c=!1,h=0,p=!1,m='arraybuffer',f=7e3,v=2e3,b=()=>{if(c)return;t.assertNonNullable(l);const e=ec(l);let i;if(e<v)return i=v-e,void setTimeout(b,i);v*=2,v>f&&(v=f),o&&o.abort(),o=new a,g()};const S=()=>{if(!c){if(--h>=0)return b(),void(r&&r());c=!0,d&&d(),s&&s()}},g=()=>{l=tc(),o=new a,o.open('get',e);let s,r=0,h=0;const f=()=>(t.assertNonNullable(l),Math.max(l,Math.max(s||0,h||0)));if(n&&o.addEventListener('progress',(t=>{const e=tc();n.updateChunk&&t.loaded>r&&(n.updateChunk(f(),t.loaded-r),r=t.loaded,s=e)})),u&&(o.timeout=u,o.addEventListener('timeout',(()=>S()))),o.addEventListener('load',(()=>{if(c)return;t.assertNonNullable(o);const e=o.status;if(e>=200&&e<300){if(o.response.byteLength&&n){const t=o.response.byteLength-r;t&&n.updateChunk&&n.updateChunk(f(),t)}d&&d(),o&&i(o.response)}else S()})),o.addEventListener('error',(()=>{S()})),p){const e=()=>{t.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(h=tc(),o.removeEventListener('readystatechange',e))};o.addEventListener('readystatechange',e)}return o.responseType=m,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(h=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(v=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(d=t,y),send:g,abort:()=>{o&&(o.abort(),o=void 0),c=!0,d&&d()}};return y}class rc{constructor(t){this.intervals=[],this.currentRate=0,this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const r=e-t.start,a=t.end-t.start;i+=r;const n=t.bytes*r/a;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:'warn'}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}}class ac{constructor(t,e,i,s,r){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=tc(),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=sc(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=tc()-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=tc()}_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=tc();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class nc{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 rc(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=ic(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=ic(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',(()=>{var i;Boolean(t.error)&&!this.destroyed&&(e(`Video element error: ${null===(i=t.error)||void 0===i?void 0:i.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const a=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:'playing'})):a()}))};a()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ac(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,l=null,d=!1;const c=()=>{const t=a&&(!d||d===this.rep);return t||i('Not running!'),t},h=(t,e,i)=>{u&&u.abort(),u=sc(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==o||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{o=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),v()},v=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=tc()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const r=this.bufferStates[i];t=Math.min(t,r.buf),r.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,m(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else m(1)},b=e=>{let s;const a=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,d=(t,e)=>({chunkIdx:u(t),startTS:n(t),dur:o(t),discontinuity:e}),h=()=>{let t=0;if(s&&s.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,i=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=s.dur.length-1;for(;a>=0&&(r-=s.dur[a],!(r<=0));--a);t=Math.min(a,s.dur.length-1-i),t=Math.max(t,0)}return d(t,!0)},p=(t,e,i)=>{l&&l.abort(),l=sc(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{l=null})).withJSONResponse().send()};return{seek:(i,o)=>{p(e,(e=>{if(!c())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let 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)),r({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=a();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(n(t)>e)return d(t);return h()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=a(),r=t?t.chunkIdx+1:0,n=r-s.fragIndex;if(!(e<=0)){if(!t||n<0||n-e>10)return i(`Resync: offset=${n} bChunks=${e} chunk=`+JSON.stringify(t)),h();if(!(n>=e))return d(r-s.fragIndex,!1)}}}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:i=>{const{videoElement:s,logger:r}=this.params;let o,u,d,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=tc(),s=Math.min(1e4,e-i);E=i;const r=()=>{l||c()&&T.seek((()=>{c()&&(E=tc(),w(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():r()}),s):r()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(d);if(i){if(d&&i.discontinuity)return r('Detected discontinuity; restarting playback'),void(this.paused?k():(S(),this._initPlayerWith(e)));x(i)}else k()},P=(t,e)=>{if(!c()||!this.sourceBuffer)return;let i,a,n;const o=i=>{window.setTimeout((()=>{c()&&P(t,e)}),i)};if(this.sourceBuffer.updating)r('Source buffer is updating; delaying appendBuffer'),o(100);else{const u=tc(),l=s.currentTime;!this.paused&&s.buffered.length>1&&g===l&&u-y>500&&(r('Stall suspected; trying to fix'),this._fixupStall()),g!==l&&(g=l,y=u);const d=this._getBufferSizeSec();if(d>30)r(`Buffered ${d} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:d}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;r('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(i=this.sourceBuffer.buffered.start(0),a=l,a-i>4&&this.sourceBuffer.remove(i,a-3)),o(1e3)}}},$=()=>{u&&o&&(r([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(d)]),P(u,(function(){u=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{c()&&p(A(t),((e,i)=>{if(c()){if(i/=1e3,u=e,d=t,n=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{c()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},R=t=>{c()&&(e.cachedHeader=t,P(t,(()=>{o=!0,$()})))};a=!0,T.seek((e=>{c()&&(E=tc(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(d=e,w())):k())}),i),e.cachedHeader?R(e.cachedHeader):h(e.headerUrl,R,(()=>this._handleNetworkError()))},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),t.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=tc();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(n&&t>r&&ec(a)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=tc();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=sc(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;Zd(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 oc;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(oc||(oc={}));const uc=[oc.PAUSED,oc.PLAYING,oc.READY],lc=[oc.PAUSED,oc.PLAYING,oc.READY];class dc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Zl(oc.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new $d,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new xd,this._dashCb=e=>{var i,s,r,a;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:t.ErrorCategory.WTF,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,a=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),r=null!==(s=Xd(e.name))&&void 0!==s?s:Kl(e.video),n=e.bitrate/1e3,o=Object.assign({},e.video);if(!r)continue;const u={id:t,quality:r,bitrate:n,size:o};a.push({track:u,representation:e})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===oc.MANIFEST_READY&&this.videoState.setState(oc.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(a=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r!==exports.PlaybackState.STOPPED){if(!s){if(lc.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&uc.includes(i))this.seek(n.position-this.liveOffset.getTotalPausedTime());else switch(i){case oc.STOPPED:return this.videoState.startTransitionTo(oc.MANIFEST_READY),void this.dash.attachSource(Gl(this.params.source.url));case oc.MANIFEST_READY:this.videoState.startTransitionTo(oc.READY),this.prepare();break;case oc.READY:return void(r===exports.PlaybackState.PAUSED?this.videoState.setState(oc.PAUSED):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(oc.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(oc.PAUSED)}))));case oc.PLAYING:return void(r===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(oc.PAUSED),this.liveOffset.pause(),this.dash.pause()));case oc.PAUSED:return void(r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(oc.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(oc.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==oc.STOPPED&&(this.videoState.startTransitionTo(oc.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(oc.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=i=>{e.output.error$.next({id:'DashLiveProvider',category:t.ErrorCategory.WTF,message:'DashLiveProvider internal logic error',thrown:i})};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=Ad(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(Yd(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Cd(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===oc.READY&&this.videoState.setState(oc.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(oc.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===l.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(oc.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(Ed(this.video,this.params.desiredState.isLooped,i)).add(kd(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(wd(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,i)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&Ql[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case oc.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case oc.MANIFEST_READY:case oc.READY:break;case oc.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case oc.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 nc({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var e,i,s,r,a,n;const o=this.representations$.getValue(),u=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),l=null!==(r=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!l&&t.isNonNullable(u)?u:null===(a=Gd(o.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))||void 0===a?void 0:a.id,c=null===(n=o.find((({track:t})=>t.id===d)))||void 0===n?void 0:n.representation;t.assertNonNullable(c,'Representations missing'),this.dash.startPlay(c,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,`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(Gl(this.params.source.url,i))}}var cc=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}},hc=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)};class pc{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let e=!1;this._xhr.onreadystatechange=()=>{var i,s,r,a,n,o,u,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===(r=this._xhr)||void 0===r?void 0:r.status}`,`XHR response code ${null===(a=this._xhr)||void 0===a?void 0:a.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=un(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===(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 mc{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,r,a,n){this.abort((()=>{let o=0;const u=Date.now();let l=0,d=0,c=0;const h=t=>{s(mc._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=gd(p)),this._lastXhr=new pc(p,t.failoverHosts,(t=>{this._lastXhr=void 0,h(t);const e=Date.now()-u;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&h(t),0===d)return void(d=Date.now());c=t.length-l;const e=Date.now()-d;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,l=t.length,d=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=mc._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class fc{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=gd(i)),new pc(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,u,l,d,c,h,p,m,f,v,b,S,g,y,T,E,k,w;const P=t.getElementsByTagName('SegmentBase')[0],$=P&&r(P,'indexRange').split('-'),A=P&&P.getElementsByTagName('Initialization')[0],x=A&&r(A,'range').split('-');if(!x||!$){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(d=null===(l=null===(u=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===u?void 0:u.childNodes)||void 0===l?void 0:l[0])||void 0===d?void 0:d.data),h=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:h})}return}const N=Number(null===(h=t.attributes.getNamedItem('bandwidth'))||void 0===h?void 0:h.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let D;const C=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;D=C?_d(C):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:N,baseURL:R,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(S=null===(b=t.attributes.getNamedItem('codecs'))||void 0===b?void 0:b.value)&&void 0!==S?S: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!==(w=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==w?w:void 0})})),a.length?(this._representations=a,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const u=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const 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,r;const a=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let a;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');a=e.to-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.to&&(r=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*a)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new mc({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const r=this._findRef(e);if(r){if(i){this._isLastRef(r)&&e>=r.toTime&&(e=r.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),a=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:r.fromTime}this._appendVector[String(r.fromTime)]=t,this._stream.load(t,r.fromOffset,r.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=r.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const r=.1;if(s.toTime<i.to+r){const e=this._findRef(s.toTime);e&&e.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var vc;!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'}(vc||(vc={}));const bc=[vc.PAUSED,vc.PLAYING];class Sc{constructor(e){this.videoState=new Zl(vc.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new $d,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&Xd(a.name))&&void 0!==s?s:Kl(a),o=a.bandwidth/1e3,u={width:a.width,height:a.height},l=a.fps;if(!n)continue;const d={id:t,quality:n,bitrate:o,size:u,fps:l};r.push({track:d,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(vc.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&bc.includes(e)&&this.seek(a.position,a.forcePrecise),e){case vc.STOPPED:return this.videoState.startTransitionTo(vc.MANIFEST_LOADED),void this.prepare();case vc.MANIFEST_LOADED:return void this.videoState.startTransitionTo(vc.INITIAL_REPRESENTATION_SELECTED);case vc.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(vc.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case vc.METADATA_LOADED:return this.videoState.startTransitionTo(vc.READY),void this.dash.updateRefsForCurrentTime();case vc.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(vc.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(vc.PLAYING),this.playIfAllowed()));case vc.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(vc.PAUSED),this.video.pause()):(null==r?void 0:r.to)===exports.PlaybackState.PLAYING&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case vc.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(vc.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===exports.PlaybackState.PAUSED&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==vc.STOPPED&&(this.videoState.startTransitionTo(vc.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(vc.STOPPED),Yl(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=Ad(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(Yd(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Rd(this.video),this.dash=new fc({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:(e,i,s)=>{this.log({message:`[DashLite error], ${e}`}),this.dashLiteEvents.error$.next({id:e,message:i,thrown:s,category:t.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'DashProvider',category:t.ErrorCategory.WTF,message:'DashProvider internal logic error',thrown:i})},r=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},a=Cd(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),this.subscription.add(a.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==l.Applying)&&(this.videoState.getState()===vc.PLAYING||this.videoState.getState()===vc.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ed(this.video,i.isLooped,s)),this.subscription.add(kd(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(wd(this.video,i.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),n(Qd(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===vc.READY&&this.videoState.setState(vc.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(vc.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(a.playing$.subscribe((()=>{this.videoState.setState(vc.PLAYING),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.loadedMetadata$.subscribe((()=>{this.videoState.setState(vc.METADATA_LOADED)}),s)).add(a.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:e,message:i,thrown:s})=>({id:`DashLite_${e}`,category:t.ErrorCategory.WTF,message:i,thrown:s})))).subscribe(this.params.output.error$)).add(t.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i,s;const a=this.currentRepresentation$.getValue(),n=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.videoTrack.getState(),l=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),d=this.elementSize$.getValue(),c=r();let h;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!c&&t.isNonNullable(u))h=u;else{const t=hc(this.video.buffered,1e3*this.video.currentTime),s=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,r=Math.min(t/s,1);h=null===(i=Gd(n.map((({track:t})=>t)),{container:d,throughput:l,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:r,playbackRate:this.video.playbackRate,current:null===(e=n.find((({representation:t})=>t===a)))||void 0===e?void 0:e.track}))||void 0===i?void 0:i.id}return t.isNonNullable(h)?null===(s=n.find((({track:t})=>t.id===h)))||void 0===s?void 0:s.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===vc.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(vc.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?t.height<=e.height:t===e))).subscribe((t=>{const e=hc(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!r())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Yd(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=cc(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once(),t.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,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(){Zd(this.video).then((t=>{t||(this.videoState.setState(vc.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var gc,yc,Tc,Ec,kc;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(gc||(gc={})),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'}(yc||(yc={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(Tc||(Tc={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(Ec||(Ec={})),function(t){t.MP4='mp4',t.WEBM='webm'}(kc||(kc={}));var wc=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const Pc='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;var $c,Ac;let xc=!1;try{xc=Nd()&&parseInt(null!==(Ac=null===($c=navigator.userAgent.match(/Version\/(\d+)/))||void 0===$c?void 0:$c[1])&&void 0!==Ac?Ac:'',10)<16}catch(t){console.error(t)}class Nc{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var e;try{if(this.currentTask){const t=null===(e=this.currentTask.signal)||void 0===e?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:'BufferTaskQueueUnknown',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Buffer appending or removal failed',thrown:e})}},this.buffer=e,this.buffer.addEventListener('updateend',this.completeTask)}append(t,e){return id(this,void 0,void 0,(function*(){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}))}remove(t,e,i){return id(this,void 0,void 0,(function*(){return(!i||!i.aborted)&&new Promise((s=>{const r={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(r),this.pull()}))}))}abort(t){return id(this,void 0,void 0,(function*(){return new Promise((e=>{let i;i=xc&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const i=this.queue.shift();if(!i)return;if(null===(e=i.signal)||void 0===e?void 0:e.aborted)return i.callback(!1),void this.pull();this.currentTask=i;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(e){e instanceof DOMException&&'QuotaExceededError'===e.name&&'append'===s?this.bufferFull$.next(this.currentTask.data.byteLength):e instanceof DOMException&&'InvalidStateError'===e.name&&'remove'===s||this.error$.next({id:`BufferTaskQueue:${s}`,category:t.ErrorCategory.VIDEO_PIPELINE,message:'Buffer operation failed',thrown:e}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(e){const{operation:i}=e;switch(i){case'append':this.buffer.appendBuffer(e.data);break;case'remove':this.buffer.remove(e.from/1e3,e.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(e.init);break;default:t.assertNever(i)}}}var Rc,Dc=t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Rc||(Rc={}));class Cc{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 hd,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,function(t){return rd(this,arguments,(function*(){let e=t;this.requestQuic&&(e=gd(e));const i=yield yield sd(cd(e,{signal:this.abortAllController.signal}).catch(_c));return i?(this.onHeadersReceived(i.headers),yield sd(i.text())):yield sd(null)}))}.bind(this)),this.fetch=t.abortable(this.abortAllController.signal,function(e,{rangeMethod:i=Rc.HEADER,range:s,onProgress:r,priority:a='auto',signal:n,measureThroughput:o=!0}={}){var u,l,d,c;return rd(this,arguments,(function*(){let h=e;const p=new Headers;if(s)switch(i){case Rc.HEADER:p.append('Range',`${s.from}-${s.to}`);break;case Rc.PARAM:{const t=new URL(h,location.href);t.searchParams.append('bytes',`${s.from}-${s.to}`),h=t.toString();break}default:t.assertNever(i)}this.requestQuic&&(h=gd(h));let m=this.abortAllController.signal;if(n){const e=new hd;if(this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(n,'abort')).subscribe((()=>{try{e.abort()}catch(t){_c(t)}}))),this.abortAllController.signal.aborted||n.aborted)try{e.abort()}catch(t){_c(t)}m=e.signal}const f=t.now(),v=yield yield sd(cd(h,{priority:a,headers:p,signal:m}).catch(_c)),b=t.now();if(null===(u=this.throughputEstimator)||void 0===u||u.addRawRtt(b-f),!v)return yield sd(null);if(!v.ok||!v.body)return yield sd(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));this.onHeadersReceived(v.headers);const S=parseInt(null!==(l=v.headers.get('Content-Length'))&&void 0!==l?l:'',10)||s&&s.to-s.from+1||NaN;if(!S){const e=yield yield sd(v.arrayBuffer());return null===(d=this.throughputEstimator)||void 0===d||d.addRawSpeed(e.byteLength,t.now()-b),null==r||r(new DataView(e),e.byteLength),yield sd(e)}if(!r&&!o)return yield sd(v.arrayBuffer());const[g,y]=v.body.tee(),T=g.getReader();o&&(null===(c=this.throughputEstimator)||void 0===c||c.trackStream(y));let E=0;const k=new ArrayBuffer(S),w=new Uint8Array(k),P=new DataView(k);let $=!1;const A=t=>{$=!0,_c(t)},x=t.abortable(m,function({done:e,value:i}){return rd(this,arguments,(function*(){if(0===E&&this.lastRequestFirstBytes$.next(t.now()-f),m.aborted)return yield sd(void 0);e?null==r||r(P,E):i&&(w.set(i,E),E+=i.byteLength,null==r||r(P,E),yield yield sd(null==T?void 0:T.read().then(x,A)))}))}.bind(this));return yield yield sd(null==T?void 0:T.read().then(x,A)),yield sd($?null:k)}))}.bind(this)),this.fetchByteRangeRepresentation=t.abortable(this.abortAllController.signal,function(t,e,i){return rd(this,arguments,(function*(){if(t.type!==Tc.BYTE_RANGE)return yield sd(null);const{from:s,to:r}=t.initRange;let a,n,o=s,u=r,l=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,l=r+1===a,l&&(o=Math.min(a,s),u=Math.max(n,r))),o=Math.min(o,0);const d=yield yield sd(this.fetch(t.url,{rangeMethod:Rc.PARAM,range:{from:o,to:u},priority:i,measureThroughput:!1}));if(!d)return yield sd(null);const c=new DataView(d,s-o,r-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const h=e.parseInit(c);let p;if(l&&void 0!==a&&void 0!==n)p=new DataView(d,a-o,n-a+1);else{const s=e.getIndexRange(h);if(s){const e=yield yield sd(this.fetch(t.url,{rangeMethod:Rc.PARAM,range:s,priority:i,measureThroughput:!1}));if(!e)return yield sd(null);p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,h);return yield sd({dataView:new DataView(d),segments:m})}))}.bind(this)),this.fetchTemplateRepresentation=t.abortable(this.abortAllController.signal,function(t,e){return rd(this,arguments,(function*(){if(t.type!==Tc.TEMPLATE)return yield sd(null);const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield yield sd(this.fetch(i,{priority:e,measureThroughput:!1}));if(!s)return yield sd(null);const r=t.segments.map((t=>Object.assign(Object.assign({},t),{status:Ec.NONE,size:void 0})));return yield sd({segments:r,dataView:new DataView(s)})}))}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=cc(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchRepresentation(e,i,s='auto'){var r,a;return id(this,void 0,void 0,(function*(){const{type:n}=e;switch(n){case Tc.BYTE_RANGE:return null!==(r=yield this.fetchByteRangeRepresentation(e,i,s))&&void 0!==r?r:null;case Tc.TEMPLATE:return null!==(a=yield this.fetchTemplateRepresentation(e,s))&&void 0!==a?a:null;default:t.assertNever(n)}}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _c=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Ic=new TextDecoder('ascii'),Lc=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=Ic.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}},Oc={validateData:t=>'ftyp'===Ic.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Lc(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),u=4294967295&r();let l=n/a*1e3,d=t.byteOffset+t.byteLength+o;for(let t=0;t<u;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:Ec.NONE,time:{from:l,to:l+o},byte:{from:d,to:d+s-1}}),l+=o,d+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const r=new DataView(t.buffer,t.byteOffset+e);try{const i=Lc(r);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Bc,Mc;!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'}(Bc||(Bc={})),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'}(Mc||(Mc={}));const Vc={[Bc.EBML]:{type:Mc.Master},[Bc.EBMLVersion]:{type:Mc.UnsignedInteger},[Bc.EBMLReadVersion]:{type:Mc.UnsignedInteger},[Bc.EBMLMaxIDLength]:{type:Mc.UnsignedInteger},[Bc.EBMLMaxSizeLength]:{type:Mc.UnsignedInteger},[Bc.DocType]:{type:Mc.String},[Bc.DocTypeVersion]:{type:Mc.UnsignedInteger},[Bc.DocTypeReadVersion]:{type:Mc.UnsignedInteger},[Bc.Void]:{type:Mc.Binary},[Bc.Segment]:{type:Mc.Master},[Bc.SeekHead]:{type:Mc.Master},[Bc.Seek]:{type:Mc.Master},[Bc.SeekID]:{type:Mc.Binary},[Bc.SeekPosition]:{type:Mc.UnsignedInteger},[Bc.Info]:{type:Mc.Master},[Bc.TimestampScale]:{type:Mc.UnsignedInteger},[Bc.Duration]:{type:Mc.Float},[Bc.Tracks]:{type:Mc.Master},[Bc.Chapters]:{type:Mc.Master},[Bc.Cluster]:{type:Mc.Master},[Bc.Timestamp]:{type:Mc.UnsignedInteger},[Bc.SilentTracks]:{type:Mc.Master},[Bc.SilentTrackNumber]:{type:Mc.UnsignedInteger},[Bc.Position]:{type:Mc.UnsignedInteger},[Bc.PrevSize]:{type:Mc.UnsignedInteger},[Bc.SimpleBlock]:{type:Mc.Binary},[Bc.BlockGroup]:{type:Mc.Master},[Bc.EncryptedBlock]:{type:Mc.Binary},[Bc.Attachments]:{type:Mc.Master},[Bc.Tags]:{type:Mc.Master},[Bc.Cues]:{type:Mc.Master},[Bc.CuePoint]:{type:Mc.Master},[Bc.CueTime]:{type:Mc.UnsignedInteger},[Bc.CueTrackPositions]:{type:Mc.Master},[Bc.CueTrack]:{type:Mc.UnsignedInteger},[Bc.CueClusterPosition]:{type:Mc.UnsignedInteger},[Bc.CueRelativePosition]:{type:Mc.UnsignedInteger},[Bc.CueDuration]:{type:Mc.UnsignedInteger},[Bc.CueBlockNumber]:{type:Mc.UnsignedInteger},[Bc.CueCodecState]:{type:Mc.UnsignedInteger},[Bc.CueReference]:{type:Mc.Master},[Bc.CueRefTime]:{type:Mc.UnsignedInteger}},Fc=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=Uc(t,i),r=s in Vc,a=r?Vc[s].type:Mc.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),l=((n&255>>o)<<8*(o-1))+Uc(u),d=i+o;let c;return c=d+l>t.byteLength?new DataView(t.buffer,t.byteOffset+d):new DataView(t.buffer,t.byteOffset+d,l),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+l,value:c,valueSize:l}},Uc=(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},jc=(e,i)=>{switch(i){case Mc.SignedInteger:return e.getInt8(0);case Mc.UnsignedInteger:return Uc(e);case Mc.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case Mc.String:return new TextDecoder('ascii').decode(e);case Mc.UTF8:return new TextDecoder('utf-8').decode(e);case Mc.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case Mc.Master:case Mc.Binary:return e;default:t.assertNever(i)}},qc=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Fc(s);if(!e(r))return;r.type===Mc.Master&&qc(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Hc=[Bc.Info,Bc.SeekHead,Bc.Tracks,Bc.Chapters,Bc.Cluster,Bc.Cues,Bc.Attachments,Bc.Tags],Gc=[Bc.Timestamp,Bc.SilentTracks,Bc.SilentTrackNumber,Bc.Position,Bc.PrevSize,Bc.SimpleBlock,Bc.BlockGroup,Bc.EncryptedBlock],Yc={validateData:t=>{if(t.getUint32(0)!==Bc.EBML)return!1;let e,i,s;const r=Fc(t);return qc(r.value,(({tag:t,type:r,value:a})=>(t===Bc.EBMLReadVersion?e=jc(a,r):t===Bc.DocType?i=jc(a,r):t===Bc.DocTypeReadVersion&&(s=jc(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,r,a,n,o,u=!1,l=!1,d=!1;return qc(e,(({tag:t,type:e,value:c,valueSize:h})=>{if(t===Bc.SeekID){const t=jc(c,e);o=Uc(t)}else t!==Bc.SeekPosition&&(o=void 0);return t===Bc.Segment?(i=c.byteOffset,s=c.byteOffset+h):t===Bc.Info?u=!0:t===Bc.SeekHead?l=!0:t===Bc.TimestampScale?r=jc(c,e):t===Bc.Duration?a=jc(c,e):t===Bc.SeekPosition&&o===Bc.Cues?n=jc(c,e):u&&l&&Hc.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(a,'Failed to parse webm Segment duration'),r=null!=r?r:1e6,{segmentStart:Math.round(i/1e9*r*1e3),segmentEnd:Math.round(s/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:n}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,r=!1;const a=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),n=[];let o;return qc(e,(({tag:t,type:e,value:i})=>{switch(t){case Bc.Cues:s=!0;break;case Bc.CuePoint:o&&a(o)&&n.push(o),o={};break;case Bc.CueTime:o&&(o.time=jc(i,e));break;case Bc.CueTrackPositions:break;case Bc.CueClusterPosition:o&&(o.position=jc(i,e));break;default:s&&Hc.includes(t)&&(r=!0)}return!(s&&r)})),o&&a(o)&&n.push(o),n.map(((t,e)=>{const{time:s,position:r}=t,a=n[e+1];return{status:Ec.NONE,time:{from:s,to:a?a.time:i.segmentDuration},byte:{from:i.segmentStart+r,to:a?i.segmentStart+a.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{qc(t,(s=>s.tag===Bc.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Gc.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Bc.SimpleBlock,Bc.BlockGroup,Bc.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class Qc{constructor(e,i,s,r,{fetcher:a,tuning:n,getCurrentPosition:o}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new hd,this.destroyAbortController=new hd,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=t.abortable(this.destroyAbortController.signal,function(e){return rd(this,arguments,(function*(){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new Nc(this.sourceBuffer),this.subscription.add(t.fromEvent(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(e=>this.error$.next({id:'SegmentEjection',category:t.ErrorCategory.WTF,message:'Error when trying to clear segments ejected by browser',thrown:e})))),this.subscription.add(t.fromEvent(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',category:t.ErrorCategory.VIDEO_PIPELINE,message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>{if(!this.sourceBuffer)return;const e=Math.min(this.bufferLimit,Dc(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield yield sd(this.loadInit(i,'high',!0));const s=this.initData.get(i.id),r=this.segments.get(i.id);if(t.assertNonNullable(s,'No init buffer for starting representation'),t.assertNonNullable(r,'No segments for starting representation'),!(s instanceof ArrayBuffer))return yield sd(void 0);let a=0;for(const t of r)t.time.from-a>0&&this.gaps.push({representation:i.id,from:a,to:t.time.from}),a=t.time.to;t.isNonNullable(i.duration)&&i.duration-a>0&&this.gaps.push({representation:i.id,from:a,to:i.duration}),yield yield sd(this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)}))}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,function(e){return rd(this,arguments,(function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return yield sd(void 0);this.switchingToRepresentationId=e;const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);let s=this.initData.get(e);if(t.isNullable(s)?yield yield sd(this.loadInit(i,'high',!1)):s instanceof Promise&&(yield yield sd(s)),s=this.initData.get(e),!(s&&s instanceof ArrayBuffer&&this.sourceBuffer))return yield sd(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield yield sd(this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal));const r=this.getCurrentPosition();t.isNonNullable(r)&&this.maintain(r)}))}.bind(this)),this.fetcher=a,this.tuning=n,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case kc.MP4:this.containerParser=Oc;break;case kc.WEBM:this.containerParser=Yc;break;default:t.assertNever(s)}this.initData=new Map(r.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(r.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new hd,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer))return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find((t=>e>=t.time.from&&e<t.time.to));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=100,i=hc(this.sourceBuffer.buffered,e),s=r?r.time.to+t:-1/0;r&&i>=r.time.to-e+t&&(a=s)}if(isFinite(this.bufferLimit)&&Dc(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),r&&r.status!==Ec.NONE))return;let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(s,i.segmentReference.type,a),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&r)if(n.includes(r))t='high';else{const e=Bd(n,0);e&&e.time.from-r.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,i,t)}!this.allInitsLoaded&&r&&r.status===Ec.FED&&!n.length&&hc(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const o=Bd(s,-1);o&&o.status===Ec.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===o))}findSegmentStartTime(t){var e,i,s;const r=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!r)return;const a=this.segments.get(r);if(!a)return;const n=a.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===Ec.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==Tc.BYTE_RANGE)return t.slice(s,s+1);const r=t;let a=0;const n=[];for(let t=s;t<r.length&&a<=this.tuning.dash.segmentRequestSize;t++){const e=r[t];if(a+=e.byte.to+1-e.byte.from,e.status!==Ec.NONE&&e.status!==Ec.PARTIALLY_EJECTED)break;n.push(e)}return n}loadSegments(e,i,s='auto'){return id(this,void 0,void 0,(function*(){if(!e.length)return;let r,a,n=e;const{type:o}=i.segmentReference;switch(o){case Tc.BYTE_RANGE:r=i.segmentReference.url,a={from:Bd(e,0).byte.from,to:Bd(e,-1).byte.to};break;case Tc.TEMPLATE:{const t=Bd(e,0);r=new URL(t.url,i.segmentReference.baseUrl).toString(),n=[t];break}default:t.assertNever(o)}for(const t of n)t.status=Ec.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:i.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield t.abortable(u,function(){return rd(this,arguments,(function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield sd(new Promise((t=>setTimeout(t,e))))}))}.bind(this))(),u.aborted))for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.fetcher.fetch(r,{rangeMethod:Rc.PARAM,range:a,onProgress:(e,s)=>{if(!u.aborted)try{this.onSomeDataLoaded(e,i.id,a?a.from:0,s,u)}catch(e){this.error$.next({id:'SegmentFeeding',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Error when feeding segments',thrown:e})}},signal:u,priority:s}).then((()=>this.failedDownloads=0),(t=>{for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment);this.onSegmentDownloadError(t)}))}))}onSegmentDownloadError(e){var i;let s=!1;const r=this.getCurrentPosition();if(this.sourceBuffer&&t.isNonNullable(r)){s=hc(null===(i=this.sourceBuffer)||void 0===i?void 0:i.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,s||this.error$.next({id:'SegmentDownload',category:t.ErrorCategory.NETWORK,message:'Error when fetching segments',thrown:e})}onSomeDataLoaded(t,e,i,s,r){if(!this.activeSegments.size)return;const a=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=Ec.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===Ec.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=Ec.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const u=o.segmentReference.type,l=t.byteLength;for(const o of this.activeSegments){const{segment:d}=o,c=u===Tc.BYTE_RANGE,h=c?d.byte.to-d.byte.from+1:l;if(o.representationId!==e)continue;if(!(!c||d.byte.from>=i&&d.byte.to<i+t.byteLength))continue;if(r.aborted){a(o);continue}const p=c?d.byte.from-i:0,m=p<s,f=(c?d.byte.to-i:t.byteLength)<=s;if(d.status===Ec.DOWNLOADING&&m&&f){d.status=Ec.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,h);this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?n(o):a(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(h,s-p),o.loadedBytes>o.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),i=o.loadedBytes===h?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(d.status=Ec.PARTIALLY_FED,o.feedingBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,r).then((t=>{if(r.aborted)a(o);else if(t)o.fedBytes+=i.byteLength,o.fedBytes===h&&n(o);else{if(o.feedingBytes<h)return;a(o)}})))}}}abortSegment(t){t.status===Ec.PARTIALLY_FED||t.status===Ec.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=Ec.NONE)),t.status=Ec.PARTIALLY_EJECTED):t.status=Ec.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const r=s instanceof Promise;e||(e=r),null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=Pc((()=>ql(this.loadInit(i,'low',!1),(()=>this.initLoadIdleCallback=null)))))}loadInit(e,i='auto',s=!1){return id(this,void 0,void 0,(function*(){const r=this.tuning.dash.useFetchPriorityHints?i:'auto',a=(!s&&this.failedDownloads>0?t.abortable(this.destroyAbortController.signal,function(){return rd(this,arguments,(function*(){const e=t.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield sd(new Promise((t=>setTimeout(t,e))))}))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r))).then((t=>{if(!t)return;const{dataView:i,segments:s}=t,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(e.id,r),this.segments.set(e.id,s)})).then((()=>this.failedDownloads=0),(i=>{this.initData.set(e.id,null),s&&this.error$.next({id:'LoadInits',category:t.ErrorCategory.WTF,message:'loadInit threw',thrown:i})}));return this.initData.set(e.id,a),a}))}pruneBuffer(e){return id(this,void 0,void 0,(function*(){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=t=>{var e;a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;r+=i};for(const t of s){if(t.time.to>=i||r>=e)break;t.status===Ec.FED&&u(t)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const t of s){if(t.time.from<i+this.forwardBufferTarget||r>e)break;t.status===Ec.FED&&u(t)}}if(o=isFinite(a)&&isFinite(n),!o)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),i=1e3*this.sourceBuffer.buffered.end(t);for(const t of s)if(t.status===Ec.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(i)){a=e,n=i;break}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a,n)}))}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),e=t instanceof ArrayBuffer?t:void 0;this.sourceBufferTaskQueue.abort(e)}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),r=1e3*this.sourceBuffer.buffered.end(t);if(!(r<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&r>=i.time.to){e=void 0;break}r>i.time.from&&r<i.time.to&&(e.from=r),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(e,i){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Pc((()=>{try{this.detectGaps(e,i)}catch(e){this.error$.next({id:'GapDetection',category:t.ErrorCategory.WTF,message:'detectGaps threw',thrown:e})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(t)),s=Math.round(1e3*this.sourceBuffer.buffered.end(t));e.push({from:i,to:s})}for(const t of this.segments.values())for(const i of t){const{status:t}=i;if(t!==Ec.FED&&t!==Ec.PARTIALLY_EJECTED)continue;const s=Math.floor(i.time.from),r=Math.ceil(i.time.to),a=e.some((t=>t.from-1<=s&&t.to+1>=r)),n=e.some((t=>s>=t.from-1&&s<=t.to+1||r>=t.from-1&&r<=t.to+1));a||(i.status=n?Ec.PARTIALLY_EJECTED:Ec.NONE)}}}const zc=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},Wc=(e,i)=>{let s=e;s=s.replaceAll('$$','$');const r={RepresentationID:i.representationId,Number:i.segmentNumber,Bandwidth:i.bandwidth,Time:i.segmentTime};for(const[e,i]of Object.entries(r)){const r=new RegExp(`\\$${e}(?:%0(\\d+)d)?\\$`,'g');s=s.replaceAll(r,((e,s)=>t.isNullable(i)?e:t.isNullable(s)?i:i.padStart(parseInt(s,10),'0')))}return s},Jc=(e,i)=>{var s,r,a,n,o,u,l,d,c,h,p,m,f,v,b,S,g,y,T,E,k,w,P,$,A,x,N,R,D,C,_,I,L,O,B;const M={video:[],audio:[],text:[]},V=(new DOMParser).parseFromString(e,'application/xml').children[0],F=V.getElementsByTagName('Period')[0],U=F.children;let j;const q=V.getAttribute('mediaPresentationDuration'),H=F.getAttribute('duration');if(q)j=zc(q);else if(H){const e=zc(H);t.isNonNullable(e)&&(j=e)}let G=0;const Y=null!==(r=null===(s=V.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==r?r:[],Q=Y.includes(yc.WEBM_AS_IN_FFMPEG)||Y.includes(yc.WEBM_AS_IN_SPEC)?kc.WEBM:kc.MP4;for(const t of U){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==e?void 0:e.split('/')[0],V=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],F=t.querySelectorAll('Representation');if('text'!==r)for(const a of F){const n=null!==(u=a.getAttribute('mimeType'))&&void 0!==u?u:e,o=null!==(d=null!==(l=a.getAttribute('codecs'))&&void 0!==l?l:s)&&void 0!==d?d:'',F=null!==(h=null!==(c=a.getAttribute('contentType'))&&void 0!==c?c:null==n?void 0:n.split('/')[0])&&void 0!==h?h:r,U=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],q=parseInt(null!==(f=a.getAttribute('width'))&&void 0!==f?f:'',10),H=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),Q=parseInt(null!==(b=a.getAttribute('bandwidth'))&&void 0!==b?b:'',10)/1e3,z=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',W=null!==(g=a.getAttribute('quality'))&&void 0!==g?g:void 0,J=z?_d(z):void 0,K=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(G++).toString(10)}@${'video'===F?`${H}p`:'audio'===F?`${Q}Kbps`:o}`,X=null!==(k=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',Z=new URL(X,i).toString(),tt=[...Y,...V,...U];let et;const it=a.querySelector('SegmentBase'),st=a.querySelector('SegmentTemplate');if(it){const t=null!==(P=null===(w=a.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==P?P:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},r=null===($=a.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[n,o]=r?r.split('-').map((t=>parseInt(t,10))):[],u=r?{from:n,to:o}:void 0;et={type:Tc.BYTE_RANGE,url:Z,initRange:s,indexRange:u}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(A=a.getAttribute('id'))&&void 0!==A?A:void 0,bandwidth:null!==(x=a.getAttribute('bandwidth'))&&void 0!==x?x:void 0},e=parseInt(null!==(N=st.getAttribute('timescale'))&&void 0!==N?N:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),r=null!==(C=parseInt(null!==(D=st.getAttribute('startNumber'))&&void 0!==D?D:'',10))&&void 0!==C?C:1,n=Wc(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(_=st.querySelectorAll('SegmentTimeline S'))&&void 0!==_?_:[],u=[];let l=r,d=0;for(const i of o){const r=1e3*parseInt(null!==(I=i.getAttribute('d'))&&void 0!==I?I:'',10),a=parseInt(null!==(L=i.getAttribute('r'))&&void 0!==L?L:'',10)||0,n=null!==(B=parseInt(null!==(O=i.getAttribute('t'))&&void 0!==O?O:'',10))&&void 0!==B?B:void 0;for(let i=0;i<a+1;i++){const i=Wc(s,Object.assign(Object.assign({},t),{segmentNumber:l.toString(10),segmentTime:n.toString(10)})),a=n?n/e:d;d+=r/e;const o=d;l++,u.push({time:{from:a,to:o},url:i})}}et={type:Tc.TEMPLATE,baseUrl:Z,initUrl:n,segments:u}}}if(!F||!n)continue;const rt={video:gc.VIDEO,audio:gc.AUDIO,text:gc.TEXT}[F];rt&&M[rt].push({id:K,kind:rt,segmentReference:et,profiles:tt,duration:j,bitrate:Q,mime:n,codecs:o,width:q,height:H,fps:J,quality:W})}}return{duration:j,container:Q,representations:M}},Kc=['timeupdate','progress','play','seeked','stalled'];var Xc,Zc;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Xc||(Xc={}));class th{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new Zl(Xc.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 hd,this.initManifest=t.abortable(this.destroyController.signal,function(e,i){return rd(this,arguments,(function*(){this.element=e,this.state$.startTransitionTo(Xc.MANIFEST_LOADED);const s=yield yield sd(this.fetcher.fetchManifest(i).catch((e=>this.error$.next({id:'LoadManifest',category:t.ErrorCategory.NETWORK,message:'Failed to load manifest',thrown:e}))));if(!s)return yield sd(null);let r;try{r=Jc(null!=s?s:'',i)}catch(e){this.error$.next({id:'ManifestParsing',category:t.ErrorCategory.PARSER,message:'Failed to parse MPD manifest',thrown:e})}if(!r)return yield sd(null);const a=({mime:t,codecs:i})=>{var s,r,a;return Boolean((null===(s=e.canPlayType)||void 0===s?void 0:s.call(e,t))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${t}; codecs="${i}"`)))};return this.manifest=Object.assign(Object.assign({},r),{representations:un(Object.entries(r.representations).map((([t,e])=>[t,e.filter(a)])))}),this.manifest.representations.video.length?this.state$.setState(Xc.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',category:t.ErrorCategory.PARSER,message:'No playable video representations'}),yield sd(this.manifest)}))}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,function(e,i){return rd(this,arguments,(function*(){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(Xc.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new Qc(gc.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],t.isNonNullable(i)&&(this.audioBufferManager=new Qc(gc.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const r=t.merge(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(t.map((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),a=t.merge(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(t.map((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(t.merge(this.forceEnded$,t.combine({allBuffersFull:r,someBufferEnded:a}).pipe(t.filter((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var e;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(e){this.error$.next({id:'EndOfStream',category:t.ErrorCategory.VIDEO_PIPELINE,message:'Failed to end MediaSource stream',thrown:e})}}))),this.subscription.add(t.merge(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield yield sd(new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})))),t.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&t.isNonNullable(i)?yield yield sd(Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)])):yield yield sd(this.videoBufferManager.startWith(e)),this.state$.setState(Xc.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...Kc.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(e=>{this.error$.next({id:'DashVKPlayer',category:t.ErrorCategory.WTF,message:'Internal logic error',thrown:e})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&wc(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}))}.bind(this)),this.tick=()=>{var e,i;if(!this.element||!this.videoBufferManager)return;const s=1e3*this.element.currentTime;this.videoBufferManager.maintain(s),null===(e=this.audioBufferManager)||void 0===e||e.maintain(s),!this.videoBufferManager.gaps.length&&!(null===(i=this.audioBufferManager)||void 0===i?void 0:i.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(e=>{this.error$.next({id:'GapWatchdog',category:t.ErrorCategory.WTF,message:'Error handling gaps',thrown:e})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Cc({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}switchRepresentation(t,e){return id(this,void 0,void 0,(function*(){const i={[gc.VIDEO]:this.videoBufferManager,[gc.AUDIO]:this.audioBufferManager,[gc.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}))}seek(e,i){var s,r,a,n,o;let u;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),u=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(a=null===(r=this.audioBufferManager)||void 0===r?void 0:r.findSegmentStartTime(e))&&void 0!==a?a:e),wc(this.element.buffered,u)||(this.videoBufferManager.abort(),null===(n=this.audioBufferManager)||void 0===n||n.abort()),this.videoBufferManager.maintain(u),null===(o=this.audioBufferManager)||void 0===o||o.maintain(u),this.element.currentTime=u/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Xc.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=[];for(const i of this.bufferManagers)for(const s of i.gaps)i.playingRepresentation$.getValue()===s.representation&&s.from<=t&&s.to>t&&(1e3*this.element.duration-s.to<this.tuning.endGapTolerance?e.push(1/0):e.push(s.to));if(e.length){const t=Math.max(...e);t===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=t/1e3}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Zc||(Zc={}));const eh=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?Xd(a):void 0)&&void 0!==n?n:Kl({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},ih=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=Bd(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:Bd(t,-1)};class sh{constructor(e){this.subscription=new t.Subscription,this.videoState=new Zl(Zc.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new $d,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Hd,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(r.state===l.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==Zc.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(r.position,r.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===Zc.STOPPED)return this.videoState.startTransitionTo(Zc.READY),void this.prepare();switch(e){case Zc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Zc.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Zc.PLAYING),this.playIfAllowed()));case Zc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Zc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Zc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Zc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Zc.STOPPED&&(this.videoState.startTransitionTo(Zc.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(Zc.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=Ad(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Yd(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new th({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=Cd(this.video),r=i=>{e.error$.next({id:'DashVKProvider',category:t.ErrorCategory.WTF,message:'DashVKProvider internal logic error',thrown:i})},a=(t,e)=>this.subscription.add(t.subscribe(e,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once(),t.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ed(this.video,i.isLooped,r)),this.subscription.add(kd(this.video,i.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(wd(this.video,i.playbackRate,s.playbackRateState$,r)),a(Qd(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState(Zc.PLAYING),Yl(i.playbackState,exports.PlaybackState.PLAYING)}),r)).add(s.pause$.subscribe((()=>{this.videoState.setState(Zc.PAUSED),Yl(i.playbackState,exports.PlaybackState.PAUSED)}),r)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===Zc.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===Xc.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Zc.READY)})));const n=i=>e.error$.next({id:'RepresentationSwitch',category:t.ErrorCategory.WTF,message:'Switching representations threw',thrown:i});this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var s,r,a,o,u,l,d,c;const h=this.player.state$.getState(),p=this.player.state$.getTransition();if(h===Xc.NONE||!this.videoTracks.length)return;const m=h===Xc.MANIFEST_LOADED&&!p,f=h===Xc.REPRESENTATION_SELECTED&&!p,v=i.autoVideoTrackSwitching.getState(),b=i.videoTrack.getState(),S=null===(s=this.videoTracks.find((({track:{id:t}})=>t===b)))||void 0===s?void 0:s.track,g=e.currentVideoTrack$.getValue(),y=hc(this.video.buffered,1e3*this.video.currentTime),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),k=Math.max(S&&!v&&null!==(a=null===(r=this.audioRepresentations.get(S.id))||void 0===r?void 0:r.bitrate)&&void 0!==a?a:0,g&&null!==(u=null===(o=this.audioRepresentations.get(g.id))||void 0===o?void 0:o.bitrate)&&void 0!==u?u:0),w=Gd(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),reserve:k,forwardBufferHealth:E,current:g,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),P=v?null!=w?w:S:null!=S?S:w;if(i.autoVideoTrackSwitching.getTransition()&&(i.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),m){const e=P&&(null===(l=this.videoTracks.find((({track:t})=>t===P)))||void 0===l?void 0:l.representation);t.assertNonNullable(e),this.player.initRepresentations(e.id,null===(d=this.audioRepresentations.get(e.id))||void 0===d?void 0:d.id)}else if(f){const t=P&&(null===(c=this.videoTracks.find((({track:t})=>t===P)))||void 0===c?void 0:c.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(gc.VIDEO,t.id).catch(n),e&&this.player.switchRepresentation(gc.AUDIO,e.id).catch(n)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}prepare(){return id(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);if(!t)return;this.videoTracks=[];const e=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),i=Array.from(t.representations.video).sort(((t,e)=>e.bitrate-t.bitrate));for(const t of i){const s=eh(t);if(s){this.videoTracks.push({track:s,representation:t});const r=ih(e,i,t);r&&this.audioRepresentations.set(t.id,r)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Zd(this.video).then((t=>{t||(this.videoState.setState(Zc.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const rh={};var ah;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ah||(ah={}));const nh=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class oh{constructor(e){this.subscription=new t.Subscription,this.videoState=new Zl(ah.INITIALIZING),this.textTracksManager=new $d,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!==ah.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&this.seek(r.position),i){case exports.PlaybackState.STOPPED:switch(e){case ah.STOPPED:break;case ah.READY:case ah.PLAYING:case ah.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case ah.PLAYING:break;case ah.STOPPED:this.prepare();break;case ah.READY:case ah.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case ah.PAUSED:break;case ah.STOPPED:this.prepare();break;case ah.READY:this.videoState.setState(ah.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case ah.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=Ad(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Yd(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 e=!1;const s=i=>{e||this.params.output.error$.next({id:'timeout'===i?'HlsJsTimeout':'HlsJsLoadError',category:t.ErrorCategory.NETWORK,message:'Failed to load Hls.js',thrown:i}),e=!0},r=window.setTimeout((()=>s('timeout')),5e3);ql(Promise.resolve().then((function(){return i(require('hls.js'))})).then((t=>{e||(rh.Hls=t.default,rh.Events=t.default.Events,this.init())}),s),(()=>{window.clearTimeout(r),e=!0}))}init(){t.assertNonNullable(rh.Hls,'hls.js not loaded'),this.hls=new rh.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ah.STOPPED)}subscribe(){t.assertNonNullable(rh.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=e=>{i.error$.next({id:'HlsJsProvider',category:t.ErrorCategory.WTF,message:'HlsJsProvider internal logic error',thrown:e})},r=Cd(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,i.position$),a(r.durationChange$,i.duration$),a(r.ended$,i.endedEvent$),a(r.looped$,i.loopedEvent$),a(r.error$,i.error$),a(r.isBuffering$,i.isBuffering$),a(r.currentBuffer$,i.currentBuffer$),a(r.loadStart$,i.firstBytesEvent$),a(r.playing$,i.firstFrameEvent$),a(r.canplay$,i.canplay$),a(r.seeked$,i.seekedEvent$),this.subscription.add(Ed(this.video,e.isLooped,s)),this.subscription.add(kd(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(wd(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(nh(this.hls,rh.Events.ERROR).subscribe((e=>{var s;e.fatal&&i.error$.next({id:['HlsJsFatal',e.type,e.details].join('_'),category:t.ErrorCategory.WTF,message:`HlsJs fatal ${e.type} ${e.details}, ${null===(s=e.err)||void 0===s?void 0:s.message} ${e.reason}`,thrown:e.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(ah.PLAYING),Yl(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(ah.PAUSED),Yl(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===ah.READY&&this.videoState.setState(ah.READY),this.videoState.getState()===ah.PLAYING&&this.playIfAllowed()}),s)),a(nh(this.hls,rh.Events.MANIFEST_PARSED).pipe(t.map((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=Xd(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:Kl({width:a,height:n});if(!o)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,l={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:u};return this.trackLevels.set(r,{track:l,level:e}),t.push(l),t}),[])))),i.availableVideoTracks$),a(nh(this.hls,rh.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>Yd(t)))),i.hostname$),this.subscription.add(Td(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=nh(this.hls,rh.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(Td(e.videoTrack,(()=>{var t;return null===(t=n(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const r=this.hls.levels.indexOf(s),a=this.hls.currentLevel,n=this.hls.levels[a];!n||s.bitrate>n.bitrate?this.hls.nextLevel=r:(this.hls.loadLevel=r,this.hls.loadLevel=r)}),{changed$:o.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),a(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(ah.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return id(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(ah.PLAYING);(yield Zd(this.video))||(this.videoState.setState(ah.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(ah.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(ah.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}var uh=t=>id(void 0,void 0,void 0,(function*(){const e=yield cd(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0}));const lh=t=>{let e=null;if(t.QUALITY&&(e=Xd(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=Kl({width:i,height:s})}return null!=e?e:null},dh=(t,e=t)=>id(void 0,void 0,void 0,(function*(){var i;const s=yield cd(t),r=(yield s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=un(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,u=lh(n);let l;n.BANDWIDTH&&(l=parseInt(n.BANDWIDTH,10)/1e3||void 0),!l&&n['AVERAGE-BANDWIDTH']&&(l=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const d=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let c;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const h=new URL(r[++t],e).toString();u&&a.push({id:o,quality:u,url:h,bandwidth:l,size:c,fps:d})}return a}));var ch,hh,ph;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(ch||(ch={}));class mh{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new Zl(ch.STOPPED),this.textTracksManager=new $d,this.manifests$=new t.ValueSubject([]),this.liveOffset=new xd,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==ch.STOPPED&&(this.videoState.startTransitionTo(ch.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(ch.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===ch.STOPPED)return this.videoState.startTransitionTo(ch.READY),void this.prepare();if(r||a){const t=this.videoState.getState();return this.videoState.setState(ch.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(ch.READY),this.seek(n.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case ch.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(ch.PAUSED),this.liveOffset.pause(),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ch.PLAYING),this.playIfAllowed()));case ch.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ch.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ch.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ch.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&&(Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case ch.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Ad(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]),dh(Gl(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',category:t.ErrorCategory.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:e}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Yd(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'HlsLiveProvider',category:t.ErrorCategory.WTF,message:'HlsLiveProvider internal logic error',thrown:i})},r=Cd(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(kd(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wd(this.video,i.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(ch.PLAYING),Yl(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(ch.PAUSED),Yl(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===ch.READY&&this.videoState.setState(ch.READY),this.videoState.getState()===ch.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Yd(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===ch.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===l.Requested&&this.seek(e.position)}),s)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e,i;const s=null===(i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate)||void 0===e?void 0:e.call(t))||void 0===i?void 0:i.getTime();this.manifestStartTime$.next(s||void 0)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=Gl(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',i),this.video.load(),uh(i).then((e=>{var s;if(t.isNullable(e)){const e=null!==(s=this.params.source.maxSeekBackTime)&&void 0!==s?s:this.maxSeekBackTime$.getValue();if(t.isNullable(e)||!isFinite(e))try{cd(i).then((t=>t.text())).then((e=>{var s;const r=null===(s=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(e))||void 0===s?void 0:s[1];if(r){const e=new URL(r,i).toString();uh(e).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(e)}))}playIfAllowed(){Zd(this.video).then((t=>{t||(this.videoState.setState(ch.PAUSED),this.liveOffset.pause(),Yl(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'}(hh||(hh={}));class fh{constructor(e){this.subscription=new t.Subscription,this.videoState=new Zl(hh.STOPPED),this.textTracksManager=new $d,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==hh.STOPPED&&(this.videoState.startTransitionTo(hh.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(hh.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===hh.STOPPED)return this.videoState.startTransitionTo(hh.READY),void this.prepare();if(r||a){const t=this.videoState.getState();this.videoState.setState(hh.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 hh.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(hh.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(hh.PLAYING),this.playIfAllowed()));case hh.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(hh.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case hh.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(hh.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case hh.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=Ad(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(Yd(this.params.source.url)),dh(this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(e=>this.params.output.error$.next({id:'ExtractHlsQualities',category:t.ErrorCategory.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:e}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'HlsProvider',category:t.ErrorCategory.WTF,message:'HlsProvider internal logic error',thrown:i})},r=Cd(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),this.subscription.add(Ed(this.video,i.isLooped,s)),this.subscription.add(kd(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wd(this.video,i.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(hh.PLAYING),Yl(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(hh.PAUSED),Yl(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===hh.READY&&this.videoState.setState(hh.READY),this.videoState.getState()===hh.PLAYING&&this.playIfAllowed()}),s).add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Yd(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===hh.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===l.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){Zd(this.video).then((t=>{t||(this.videoState.setState(hh.PAUSED),Yl(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'}(ph||(ph={}));class vh{constructor(e){this.subscription=new t.Subscription,this.videoState=new Zl(ph.STOPPED),this.trackUrls={},this.textTracksManager=new $d,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!==ph.STOPPED&&(this.videoState.startTransitionTo(ph.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(ph.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(e===ph.STOPPED)return this.videoState.startTransitionTo(ph.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&this.seek(a.position),e){case ph.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(ph.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ph.PLAYING),this.playIfAllowed()));case ph.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ph.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case ph.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ph.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=Ad(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.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'MpegProvider',category:t.ErrorCategory.WTF,message:'MpegProvider internal logic error',thrown:i})},r=Cd(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),this.subscription.add(Ed(this.video,i.isLooped,s)),this.subscription.add(kd(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(wd(this.video,i.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(ph.PLAYING),Yl(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(ph.PAUSED),Yl(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===ph.READY&&this.videoState.setState(ph.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()===ph.PLAYING&&this.playIfAllowed()}),s)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:r}=this.trackUrls[s];t.assertNonNullable(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=gd(r)),this.video.setAttribute('src',r),this.video.load(),this.params.output.hostname$.next(Yd(r))}playIfAllowed(){Zd(this.video).then((t=>{t||(this.videoState.setState(ph.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}const bh=['stun:videostun.mycdn.me:80'],Sh=()=>null;class gh{constructor(t,e){this.ws=null,this.peerConnection=null,this.serverUrl='',this.streamKey='',this.stream=null,this.signalingType='JOIN',this.retryCount=0,this.externalStartCallback=Sh,this.externalStopCallback=Sh,this.externalErrorCallback=Sh,this.options=this.normalizeOptions(e);const i=t.split('/');this.serverUrl=i.slice(0,i.length-1).join('/'),this.streamKey=i[i.length-1]}onStart(t){try{this.externalStartCallback=t}catch(t){this.handleSystemError(t)}}onStop(t){try{this.externalStopCallback=t}catch(t){this.handleSystemError(t)}}onError(t){try{this.externalErrorCallback=t}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(t){this.handleSystemError(t)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(t){try{if(!this.ws)return;this.ws=null,t.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(t){try{this.externalErrorCallback(new Error(t.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(t){try{const e=this.parseMessage(t.data);switch(e.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(e);break;case'UPDATE':this.handleUpdateMessage(e);break;case'STATUS':this.handleStatusMessage(e)}}catch(t){this.handleRTCError(t)}}handleJoinMessage(t){switch(t.inviteType){case'ANSWER':this.handleAnswer(t.sdp);break;case'CANDIDATE':this.handleCandidate(t.candidate)}}handleStatusMessage(t){switch(t.status){case'UNPUBLISHED':this.handleUnpublished()}}handleUpdateMessage(t){return id(this,void 0,void 0,(function*(){try{const e=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(e)),this.handleAnswer(t.sdp)}catch(t){this.handleRTCError(t)}}))}handleLogin(){return id(this,void 0,void 0,(function*(){try{const t={iceServers:[{urls:bh}]};this.peerConnection=new RTCPeerConnection(t),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const e=yield this.createOffer();yield this.peerConnection.setLocalDescription(e),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:e.sdp,callSupport:!1})}catch(t){this.handleRTCError(t)}}))}handleAnswer(t){return id(this,void 0,void 0,(function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:t})))}catch(t){this.handleRTCError(t)}}))}handleCandidate(t){return id(this,void 0,void 0,(function*(){if(t)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(t))}catch(t){this.handleRTCError(t)}}))}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(t){this.handleRTCError(t)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',category:t.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(t){return id(this,void 0,void 0,(function*(){const e=t.streams[0];this.stream&&this.stream.id===e.id||(this.stream=e,this.externalStartCallback(this.stream))}))}onPeerConnectionIceCandidate(t){t.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:t.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const t=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(t)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return id(this,void 0,void 0,(function*(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const t=yield this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),e=t.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(e))throw new Error('No h264 codec support error');return t}))}handleRTCError(t){try{this.externalErrorCallback(t||new Error('RTC connection error'))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(t){this.handleSystemError(t)}}send(t){this.ws&&this.ws.send(JSON.stringify(t))}parseMessage(t){try{return JSON.parse(t)}catch(t){throw new Error('Can not parse socket message')}}closeConnections(){const t=this.ws;t&&(this.ws=null,t.close(1e3)),this.removePeerConnection()}removePeerConnection(){let t=this.peerConnection;t&&(this.peerConnection=null,t.close(),t.ontrack=null,t.onicecandidate=null,t.oniceconnectionstatechange=null,t=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(t={}){const e={stunServerList:bh,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var yh,Th,Eh,kh,wh,Ph,$h,Ah,xh,Nh,Rh,Dh,Ch,_h,Ih,Lh,Oh,Bh;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(yh||(yh={}));class Mh{constructor(e){this.videoState=new Zl(yh.STOPPED),this.maxSeekBackTime$=new t.ValueSubject(0),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!==yh.STOPPED&&(this.videoState.startTransitionTo(yh.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(yh.STOPPED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===yh.STOPPED)return this.videoState.startTransitionTo(yh.READY),void this.prepare();if(r)this.prepare();else switch(e){case yh.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(yh.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(yh.PLAYING),this.playIfAllowed()));case yh.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(yh.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case yh.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(yh.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=Ad(e.container),this.liveStreamClient=new gh(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:i}=this.params,s=i=>{e.error$.next({id:'WebRTCLiveProvider',category:t.ErrorCategory.WTF,message:'WebRTCLiveProvider internal logic error',thrown:i})};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)}`})}));const r=Cd(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe((t=>{e.duration$.next(t===1/0?0:t)}))).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===yh.READY&&this.videoState.setState(yh.READY)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(yh.PAUSED)}),s)).add(r.playing$.subscribe((()=>{this.videoState.setState(yh.PLAYING)}),s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(kd(this.video,i.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe((s=>{switch(s.to){case yh.STOPPED:e.position$.next(0),e.duration$.next(0),i.playbackState.setState(exports.PlaybackState.STOPPED);break;case yh.READY:break;case yh.PAUSED:i.playbackState.setState(exports.PlaybackState.PAUSED);break;case yh.PLAYING:i.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(s.to)}}),s)).add(t.merge(i.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s))}onLiveStreamStart(t){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Yd(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=t,Yl(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(yh.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',category:t.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Zd(this.video).then((t=>{t||(this.videoState.setState(yh.PAUSED),Yl(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}}class Vh{constructor(t){this.iterator=t[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error('Iterable is completed');return this.current.value}isCompleted(){return Boolean(this.current.done)}}const Fh=Nd(),Uh=(null===(Th=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Th?void 0:Th.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),jh=document.createElement('video'),qh={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(kh=null===(Eh=window.SourceBuffer)||void 0===Eh?void 0:Eh.prototype)||void 0===kh?void 0:kh.appendBuffer)),hls:Boolean((null===(wh=jh.canPlayType)||void 0===wh?void 0:wh.call(jh,'application/x-mpegurl'))||(null===(Ph=jh.canPlayType)||void 0===Ph?void 0:Ph.call(jh,'vnd.apple.mpegURL'))),webrtc:Boolean(window.RTCPeerConnection)},Hh={mp4:Boolean(null===($h=jh.canPlayType)||void 0===$h?void 0:$h.call(jh,'video/mp4')),webm:Boolean(null===(Ah=jh.canPlayType)||void 0===Ah?void 0:Ah.call(jh,'video/webm'))},Gh={h264:Boolean(null===(Nh=null===(xh=window.MediaSource)||void 0===xh?void 0:xh.isTypeSupported)||void 0===Nh?void 0:Nh.call(xh,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Dh=null===(Rh=window.MediaSource)||void 0===Rh?void 0:Rh.isTypeSupported)||void 0===Dh?void 0:Dh.call(Rh,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(_h=null===(Ch=window.MediaSource)||void 0===Ch?void 0:Ch.isTypeSupported)||void 0===_h?void 0:_h.call(Ch,'video/webm; codecs="vp9"')),aac:Boolean(null===(Lh=null===(Ih=window.MediaSource)||void 0===Ih?void 0:Ih.isTypeSupported)||void 0===Lh?void 0:Lh.call(Ih,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Bh=null===(Oh=window.MediaSource)||void 0===Oh?void 0:Oh.isTypeSupported)||void 0===Bh?void 0:Bh.call(Oh,'audio/webm; codecs="opus"'))},Yh=(Gh.h264||Gh.h265)&&Gh.aac,Qh=!Fh,zh=qh.hls&&Hh.mp4&&(Uh||Fh),Wh=Boolean(window.WebSocket);const Jh=2e4,Kh=3,Xh={cacheDuration:12e4},Zh={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},tp={maxPausedTime:3e4},ep={maxPausedTime:3e4};class ip{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,canplay$: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 Vh(((e,i=!1)=>e.filter((e=>{switch(e){case exports.VideoFormat.DASH:return qh.mse&&Hh.mp4&&Yh&&Qh;case exports.VideoFormat.DASH_SEP:return qh.mse&&Hh.mp4&&Yh;case exports.VideoFormat.DASH_WEBM:return qh.mse&&Hh.webm&&Gh.vp9&&Gh.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return qh.mse&&Hh.mp4&&Yh;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return zh||i&&qh.mse&&Hh.mp4&&Yh;case exports.VideoFormat.MPEG:return Hh.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return qh.webrtc&&Wh&&Gh.h264&&(Hh.mp4||Hh.webm);default:return t.assertNever(e)}})))(s.filter((i=>t.isNonNullable(e.sources[i]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Vh(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(e){this.providerError$.next({id:'ProviderNotConstructed',category:t.ErrorCategory.WTF,message:'Failed to create provider',thrown:e})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==l.None;this.params.desiredState.seekState.setState({state:l.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case n.SCREEN:return this.createScreenProvider(i);case n.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new Sc(Object.assign(Object.assign({},n),{source:s,config:Xh}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),this.params.tuning.useDashJs?new Kd(Object.assign(Object.assign({},n),{source:s,format:e,config:ep})):new sh(Object.assign(Object.assign({},n),{source:s}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),zh||!this.params.tuning.useHlsJs?new fh(Object.assign(Object.assign({},n),{source:s})):new oh(Object.assign(Object.assign({},n),{source:s}))}case exports.VideoFormat.HLS_LIVE:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new mh(Object.assign(Object.assign({},n),{source:s,config:tp}))}case exports.VideoFormat.MPEG:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new vh(Object.assign(Object.assign({},n),{source:s}))}case exports.VideoFormat.DASH_LIVE:{const s=this.applyFailoverHost(i[e]);return t.assertNonNullable(s),new dc(Object.assign(Object.assign({},n),{source:s,config:Zh}))}case exports.VideoFormat.WEB_RTC_LIVE:{const n=this.applyFailoverHost(i[e]);return t.assertNonNullable(n),new Mh({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(o),new ed({connection:o,meta:a,container:s,source:i,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?n.CHROMECAST:n.SCREEN}chooseFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case n.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.next();case n.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case n.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case n.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}applyFailoverHost(t){if(void 0===this.failoverIndex)return t;const e=this.params.failoverHosts[this.failoverIndex];if(!e)return t;const i=t=>{const i=new URL(t);return i.host=e,i.toString()};if(void 0===t)return t;if('type'in t){if('raw'===t.type)return t;if('url'===t.type)return Object.assign(Object.assign({},t),{url:i(t.url)})}return un(Object.entries(t).map((([t,e])=>[t,i(e)])))}initProviderErrorHandling(){const e=new t.Subscription;let i=!1,s=0;var r;return e.add(t.merge(this.providerOutput.error$,(r={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Jh,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(t.filter((({type:t})=>void 0!==t)))},new t.Observable((e=>{const i=new t.Subscription,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(t.map((({from:t,to:e})=>`${t}-${e}`))),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$,o=new t.Subject;let u=0,l='unknown';return i.add(s.subscribe((t=>{u&&window.clearTimeout(u),l=t,u=window.setTimeout((()=>o.next(t)),r.maxTransitionInterval)}))),i.add(a.subscribe((()=>{window.clearTimeout(u),l='provider change',u=0}))),i.add(n.subscribe((()=>{u&&(window.clearTimeout(u),u=window.setTimeout((()=>o.next(l)),r.maxTransitionInterval))}))),i.add(o.subscribe(e)),()=>{window.clearTimeout(u),i.unsubscribe()}}))).pipe(t.map((e=>({id:`ProviderHangup:${e}`,category:t.ErrorCategory.WTF,message:`A ${e} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),e.add(this.current$.subscribe((()=>{i=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>i=!0));e.add(s)}))),e.add(this.providerError$.subscribe((e=>{if(this.current$.getValue().destination===n.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>this.switchToNextProvider()),(()=>this.params.dependencies.chromecastInitializer.disconnect()));else{const r=e.category===t.ErrorCategory.NETWORK,a=this.params.failoverHosts.length>0&&(void 0===this.failoverIndex||this.failoverIndex<this.params.failoverHosts.length-1),n=s<Kh;a&&(r&&i||!n)?(this.failoverIndex=void 0===this.failoverIndex?0:this.failoverIndex+1,this.reinitProvider()):n?(s++,this.reinitProvider()):this.switchToNextProvider()}}))),e}}const sp=(t,e,i)=>i*e+(1-i)*t;class rp{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new jd(`raw_${s}`),this.smoothedSeries$=new jd(`smoothed_${s}`),this.reportedSeries$=new jd(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let i=0,s=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(i+=Math.pow(this.pastMeasures[t]-this.smoothed,2),s++);i/=s;const r=Math.sqrt(i),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=sp(this.slow,e,this.params.emaAlphaSlow),this.fast=sp(this.fast,e,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>a||this.smoothed<n||(t.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}var ap;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(ap||(ap={}));const np=new Map;let op=ap.RUNTIME;const up=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(up,'test'),localStorage.removeItem(up),op=ap.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(up),op=ap.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;op=ap.RUNTIME}}})();const lp=(e,i)=>{switch(op){case ap.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case ap.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case ap.RUNTIME:return void np.set(e,i);default:t.assertNever(op)}},dp=window.navigator.connection,cp=()=>{const e=null==dp?void 0:dp.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},hp=()=>{const e=null==dp?void 0:dp.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},pp=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class mp{constructor(e){var i,s;this.subscription=new t.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=mp.load('one_video_throughput')||(e.useBrowserEstimation?cp():void 0)||5e3,a=null!==(s=null!==(i=mp.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?hp():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(r),this.rtt$=new t.ValueSubject(a),this.rttAdjustedThroughput$=new t.ValueSubject(pp(r,a,e.rttPenaltyRequestSize)),this.throughput=new rp({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new rp({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=cp();e&&this.throughput.next(e);const i=hp();t.isNonNullable(i)&&this.rtt.next(i)};dp&&'onchange'in dp&&this.subscription.add(t.fromEvent(dp,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{lp('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{lp('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})=>pp(t,i,e.rttPenaltyRequestSize))),t.filter((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let i=0,s=t.now();const r=new t.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:r.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}r.add(t.fromEvent(e,'loadend').subscribe((a=>{if(200===e.status){const e=a.loaded,r=t.now(),n=e-i,o=r-s;this.addRawSpeed(n,o,1)}this.concurrentDownloads.delete(e),r.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const r=t.now();let a=0,n=t.now();const o=t=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=({done:l,value:d})=>id(this,void 0,void 0,(function*(){l?(this.addRawSpeed(s,t.now()-r,1),this.concurrentDownloads.delete(e)):d&&(s+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&t.now()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,t.now()-n,this.concurrentDownloads.size),a=0,n=t.now()),yield null==i?void 0:i.read().then(u,o))}));this.concurrentDownloads.add(e),null==i||i.read().then(u,o)}addRawSpeed(t,e,i=1){if(mp.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(e){var i;const s=(e=>{var i,s;switch(op){case ap.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case ap.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case ap.RUNTIME:return np.get(e);default:t.assertNever(op)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const fp={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],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,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const vp=({playbackState:e,seekState:i,playbackAbort$:s,looped$:r,position$:a})=>new t.Observable((n=>{let o;const u=e.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),d=e.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),c=i.stateChangeEnded$.pipe(t.filter((({to:t})=>{var i,s;return t.state===l.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===exports.PlaybackState.PLAYING}))),h=i.stateChangeEnded$.pipe(t.filter((({from:t,to:i})=>{var s,r;return t.state===l.Applying&&i.state===l.None&&(null!==(r=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:e.getState())===exports.PlaybackState.PLAYING}))),p=t.merge(u,h).pipe(t.map((()=>a.getValue())),t.filter(t.isNonNullable)),m=t.merge(t.merge(d,c,s),r).pipe(t.map((()=>a.getValue())),t.filter(t.isNonNullable));return(new t.Subscription).add(p.subscribe((t=>{o=t}))).add(m.subscribe((e=>{if(t.isNullable(o)||o===e)return;const i={from:o,to:e};o=void 0,n.next(i)})))})),bp={[n.SCREEN]:{vod:[...zh?[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:[],exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,...zh?[]:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND],exports.VideoFormat.MPEG],live:zh?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE]},[n.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM,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 Zl(exports.PlaybackState.STOPPED),seekState:new Zl({state:l.None}),volume:new Zl({volume:1,muted:!1}),videoTrack:new Zl(void 0),autoVideoTrackSwitching:new Zl(!0),autoVideoTrackLimits:new Zl({}),isLooped:new Zl(!1),playbackRate:new Zl(1),externalTextTracks:new Zl([]),currentTextTrack:new Zl(void 0),textTrackCuesSettings:new Zl({})},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({}),currentPlaybackRate$:new t.ValueSubject(1),currentBuffer$:new t.ValueSubject({start:0,end: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={inited$:new t.Subject,started$: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,canplay$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:Fd},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(fp)){const s=fp[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(e),this.chromecastInitializer=new d({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mp(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(e,i,s)=>{const r=Reflect.get(e,i,s);return'function'!=typeof r?r:(...s)=>{try{return r.apply(e,s)}catch(e){const r=s.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(i)}`,n=`Exception calling ${a} (${r.join(', ')})`;throw this.events.fatalError$.next({id:a,category:t.ErrorCategory.WTF,message:n,thrown:e}),e}}}})}initVideo(e){var i,s,r;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 ip({screenFormatsPriority:[...bp[n.SCREEN].live,...bp[n.SCREEN].vod],chromecastFormatsPriority:[...bp[n.CHROMECAST].live,...bp[n.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},failoverHosts:null!==(r=e.failoverHosts)&&void 0!==r?r:[],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,!1),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}setPlaybackRate(e){var i;t.assertNonNullable(this.providerContainer);const s=null===(i=this.providerContainer)||void 0===i?void 0:i.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({type:'external'},t)))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===l.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).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$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((()=>!this.isPlaybackStarted)),t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=t.now(),this.events.inited$.next())}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const e=this.desiredState.seekState.getState();e.state===l.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},e),{state:l.Applying})):this.events.managedError$.next({id:`WillSeekIn${e.state}`,category:t.ErrorCategory.WTF,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)=>Xl(t)?1:Xl(e)?-1:zl(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$.pipe(t.map((t=>t?{start:t.from,end:t.to}:{start:0,end:0}))).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(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((e=>({id:'NoProviders',category:t.ErrorCategory.VIDEO_PIPELINE,message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(t.once(),t.map((()=>t.now()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let r=0;const a=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),r=i.getValue()||s.getValue();return t&&!r})),t.filterChanged());this.subscription.add(a.subscribe((t=>{t?r=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})));const n=new t.Subscription;this.subscription.add(n);const o=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),n.unsubscribe(),e){case!0:{const e=new t.ValueSubject(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),n.add(vp({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:e}).pipe(t.map((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(vp({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(t.map((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(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=Gd(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(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),Vd={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Md=t})),this.providerContainer.current$.subscribe((({type:t})=>Ud('provider',t))),i.duration$.subscribe((t=>Ud('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>Ud('tracks',t))),this.events.fatalError$.subscribe(new jd('fatalError')),this.events.managedError$.subscribe(new jd('managedError')),i.position$.subscribe(new jd('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new jd('quality')),this.info.currentBuffer$.subscribe(new jd('buffer')),i.isBuffering$.subscribe(new jd('isBuffering'))].forEach((t=>this.subscription.add(t))),Ud('codecs',Object.keys(Gh).filter((t=>Gh[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.77';
6
+ "use strict";var ru=Object.create;var pa=Object.defineProperty;var su=Object.getOwnPropertyDescriptor;var au=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ou=Object.prototype.hasOwnProperty;var lu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of au(e))!ou.call(i,s)&&s!==t&&pa(i,s,{get:()=>e[s],enumerable:!(r=su(e,s))||r.enumerable});return i};var ma=(i,e,t)=>(t=i!=null?ru(nu(i)):{},lu(e||!i||!i.__esModule?pa(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),uu=require("lodash/debounce.js");const du="2.0.78",cu="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var he;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(he||(he={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var D;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(D||(D={}));var hu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class fu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||hu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(pu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const pu=i=>{switch(i){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 a.assertNever(i)}};var va=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ye=function(i){try{return!!i()}catch(e){return!0}},mu=ye,er=!mu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),so=er,ao=Function.prototype,hs=ao.call,vu=so&&ao.bind.bind(hs,hs),Ce=so?vu:function(i){return function(){return hs.apply(i,arguments)}},no=Ce,Su=no({}.toString),bu=no("".slice),tr=function(i){return bu(Su(i),8,-1)},gu=Ce,yu=ye,Tu=tr,Sr=Object,Eu=gu("".split),$u=yu(function(){return!Sr("z").propertyIsEnumerable(0)})?function(i){return Tu(i)=="String"?Eu(i,""):Sr(i)}:Sr,ir=function(i){return i==null},Pu=ir,ku=TypeError,oo=function(i){if(Pu(i))throw ku("Can't call method on "+i);return i},_u=$u,wu=oo,si=function(i){return _u(wu(i))},Au=function(){},Ct={},vi=function(i){return i&&i.Math==Math&&i},le=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof va=="object"&&va)||function(){return this}()||Function("return this")(),fs=typeof document=="object"&&document.all,Ru=typeof fs=="undefined"&&fs!==void 0,lo={all:fs,IS_HTMLDDA:Ru},uo=lo,Iu=uo.all,se=uo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Iu}:function(i){return typeof i=="function"},Nu=le,Cu=se,Sa=Nu.WeakMap,Du=Cu(Sa)&&/native code/.test(String(Sa)),ba=se,co=lo,Ou=co.all,Ke=co.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ba(i)||i===Ou}:function(i){return typeof i=="object"?i!==null:ba(i)},Lu=ye,Ue=!Lu(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),dt={},xu=le,ga=Ke,ps=xu.document,Bu=ga(ps)&&ga(ps.createElement),Ds=function(i){return Bu?ps.createElement(i):{}},Mu=Ue,Vu=ye,Fu=Ds,ho=!Mu&&!Vu(function(){return Object.defineProperty(Fu("div"),"a",{get:function(){return 7}}).a!=7}),Uu=Ue,ju=ye,fo=Uu&&ju(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Hu=Ke,Gu=String,qu=TypeError,Xe=function(i){if(Hu(i))return i;throw qu(Gu(i)+" is not an object")},Yu=er,Si=Function.prototype.call,Pe=Yu?Si.bind(Si):function(){return Si.apply(Si,arguments)},Os={},br=Os,gr=le,zu=se,ya=function(i){return zu(i)?i:void 0},ct=function(i,e){return arguments.length<2?ya(br[i])||ya(gr[i]):br[i]&&br[i][e]||gr[i]&&gr[i][e]},Wu=Ce,Ls=Wu({}.isPrototypeOf),rr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",po=le,yr=rr,Ta=po.process,Ea=po.Deno,$a=Ta&&Ta.versions||Ea&&Ea.version,Pa=$a&&$a.v8,Te,Hi;Pa&&(Te=Pa.split("."),Hi=Te[0]>0&&Te[0]<4?1:+(Te[0]+Te[1]));!Hi&&yr&&(Te=yr.match(/Edge\/(\d+)/),(!Te||Te[1]>=74)&&(Te=yr.match(/Chrome\/(\d+)/),Te&&(Hi=+Te[1])));var mo=Hi,ka=mo,Qu=ye,vo=!!Object.getOwnPropertySymbols&&!Qu(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&ka&&ka<41}),Ju=vo,So=Ju&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Ku=ct,Xu=se,Zu=Ls,ed=So,td=Object,bo=ed?function(i){return typeof i=="symbol"}:function(i){var e=Ku("Symbol");return Xu(e)&&Zu(e.prototype,td(i))},id=String,sr=function(i){try{return id(i)}catch(e){return"Object"}},rd=se,sd=sr,ad=TypeError,ht=function(i){if(rd(i))return i;throw ad(sd(i)+" is not a function")},nd=ht,od=ir,xs=function(i,e){var t=i[e];return od(t)?void 0:nd(t)},Tr=Pe,Er=se,$r=Ke,ld=TypeError,ud=function(i,e){var t,r;if(e==="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i))||Er(t=i.valueOf)&&!$r(r=Tr(t,i))||e!=="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i)))return r;throw ld("Can't convert object to primitive value")},Gi={},dd={get exports(){return Gi},set exports(i){Gi=i}},go=!0,_a=le,cd=Object.defineProperty,hd=function(i,e){try{cd(_a,i,{value:e,configurable:!0,writable:!0})}catch(t){_a[i]=e}return e},fd=le,pd=hd,wa="__core-js_shared__",md=fd[wa]||pd(wa,{}),Bs=md,Aa=Bs;(dd.exports=function(i,e){return Aa[i]||(Aa[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var vd=oo,Sd=Object,Ms=function(i){return Sd(vd(i))},bd=Ce,gd=Ms,yd=bd({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return yd(gd(e),t)},Td=Ce,Ed=0,$d=Math.random(),Pd=Td(1 .toString),yo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Pd(++Ed+$d,36)},kd=le,_d=Gi,Ra=je,wd=yo,Ad=vo,Rd=So,Tt=kd.Symbol,Pr=_d("wks"),Id=Rd?Tt.for||Tt:Tt&&Tt.withoutSetter||wd,pe=function(i){return Ra(Pr,i)||(Pr[i]=Ad&&Ra(Tt,i)?Tt[i]:Id("Symbol."+i)),Pr[i]},Nd=Pe,Ia=Ke,Na=bo,Cd=xs,Dd=ud,Od=pe,Ld=TypeError,xd=Od("toPrimitive"),Bd=function(i,e){if(!Ia(i)||Na(i))return i;var t=Cd(i,xd),r;if(t){if(e===void 0&&(e="default"),r=Nd(t,i,e),!Ia(r)||Na(r))return r;throw Ld("Can't convert object to primitive value")}return e===void 0&&(e="number"),Dd(i,e)},Md=Bd,Vd=bo,Vs=function(i){var e=Md(i,"string");return Vd(e)?e:e+""},Fd=Ue,Ud=ho,jd=fo,bi=Xe,Ca=Vs,Hd=TypeError,kr=Object.defineProperty,Gd=Object.getOwnPropertyDescriptor,_r="enumerable",wr="configurable",Ar="writable";dt.f=Fd?jd?function(e,t,r){if(bi(e),t=Ca(t),bi(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ar in r&&!r[Ar]){var s=Gd(e,t);s&&s[Ar]&&(e[t]=r.value,r={configurable:wr in r?r[wr]:s[wr],enumerable:_r in r?r[_r]:s[_r],writable:!1})}return kr(e,t,r)}:kr:function(e,t,r){if(bi(e),t=Ca(t),bi(r),Ud)try{return kr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw Hd("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var ar=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},qd=Ue,Yd=dt,zd=ar,ai=qd?function(i,e,t){return Yd.f(i,e,zd(1,t))}:function(i,e,t){return i[e]=t,i},Wd=Gi,Qd=yo,Da=Wd("keys"),Fs=function(i){return Da[i]||(Da[i]=Qd(i))},Us={},Jd=Du,To=le,Kd=Ke,Xd=ai,Rr=je,Ir=Bs,Zd=Fs,ec=Us,Oa="Object already initialized",ms=To.TypeError,tc=To.WeakMap,qi,ii,Yi,ic=function(i){return Yi(i)?ii(i):qi(i,{})},rc=function(i){return function(e){var t;if(!Kd(e)||(t=ii(e)).type!==i)throw ms("Incompatible receiver, "+i+" required");return t}};if(Jd||Ir.state){var Ae=Ir.state||(Ir.state=new tc);Ae.get=Ae.get,Ae.has=Ae.has,Ae.set=Ae.set,qi=function(i,e){if(Ae.has(i))throw ms(Oa);return e.facade=i,Ae.set(i,e),e},ii=function(i){return Ae.get(i)||{}},Yi=function(i){return Ae.has(i)}}else{var St=Zd("state");ec[St]=!0,qi=function(i,e){if(Rr(i,St))throw ms(Oa);return e.facade=i,Xd(i,St,e),e},ii=function(i){return Rr(i,St)?i[St]:{}},Yi=function(i){return Rr(i,St)}}var Eo={set:qi,get:ii,has:Yi,enforce:ic,getterFor:rc},sc=er,$o=Function.prototype,La=$o.apply,xa=$o.call,Po=typeof Reflect=="object"&&Reflect.apply||(sc?xa.bind(La):function(){return xa.apply(La,arguments)}),ac=tr,nc=Ce,ko=function(i){if(ac(i)==="Function")return nc(i)},js={},_o={},wo={}.propertyIsEnumerable,Ao=Object.getOwnPropertyDescriptor,oc=Ao&&!wo.call({1:2},1);_o.f=oc?function(e){var t=Ao(this,e);return!!t&&t.enumerable}:wo;var lc=Ue,uc=Pe,dc=_o,cc=ar,hc=si,fc=Vs,pc=je,mc=ho,Ba=Object.getOwnPropertyDescriptor;js.f=lc?Ba:function(e,t){if(e=hc(e),t=fc(t),mc)try{return Ba(e,t)}catch(r){}if(pc(e,t))return cc(!uc(dc.f,e,t),e[t])};var vc=ye,Sc=se,bc=/#|\.prototype\./,ni=function(i,e){var t=yc[gc(i)];return t==Ec?!0:t==Tc?!1:Sc(e)?vc(e):!!e},gc=ni.normalize=function(i){return String(i).replace(bc,".").toLowerCase()},yc=ni.data={},Tc=ni.NATIVE="N",Ec=ni.POLYFILL="P",Ro=ni,Ma=ko,$c=ht,Pc=er,kc=Ma(Ma.bind),nr=function(i,e){return $c(i),e===void 0?i:Pc?kc(i,e):function(){return i.apply(e,arguments)}},gi=le,_c=Po,wc=ko,Ac=se,Rc=js.f,Ic=Ro,bt=Os,Nc=nr,gt=ai,Va=je,Cc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return _c(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?gi:s?gi[t]:(gi[t]||{}).prototype,l=r?bt:bt[t]||gt(bt,t,{})[t],d=l.prototype,u,c,h,f,p,v,m,S,b;for(f in e)u=Ic(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Va(o,f),v=l[f],c&&(i.dontCallGetSet?(b=Rc(o,f),m=b&&b.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof v==typeof p)&&(i.bind&&c?S=Nc(p,gi):i.wrap&&c?S=Cc(p):n&&Ac(p)?S=wc(p):S=p,(i.sham||p&&p.sham||v&&v.sham)&&gt(S,"sham",!0),gt(l,f,S),n&&(h=t+"Prototype",Va(bt,h)||gt(bt,h,{}),gt(bt[h],f,p),i.real&&d&&(u||!d[f])&&gt(d,f,p)))},vs=Ue,Dc=je,Io=Function.prototype,Oc=vs&&Object.getOwnPropertyDescriptor,Hs=Dc(Io,"name"),Lc=Hs&&function(){}.name==="something",xc=Hs&&(!vs||vs&&Oc(Io,"name").configurable),Bc={EXISTS:Hs,PROPER:Lc,CONFIGURABLE:xc},No={},Mc=Math.ceil,Vc=Math.floor,Fc=Math.trunc||function(e){var t=+e;return(t>0?Vc:Mc)(t)},Uc=Fc,Gs=function(i){var e=+i;return e!==e||e===0?0:Uc(e)},jc=Gs,Hc=Math.max,Gc=Math.min,qc=function(i,e){var t=jc(i);return t<0?Hc(t+e,0):Gc(t,e)},Yc=Gs,zc=Math.min,Wc=function(i){return i>0?zc(Yc(i),9007199254740991):0},Qc=Wc,qs=function(i){return Qc(i.length)},Jc=si,Kc=qc,Xc=qs,Fa=function(i){return function(e,t,r){var s=Jc(e),n=Xc(s),o=Kc(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Zc={includes:Fa(!0),indexOf:Fa(!1)},eh=Ce,Nr=je,th=si,ih=Zc.indexOf,rh=Us,Ua=eh([].push),sh=function(i,e){var t=th(i),r=0,s=[],n;for(n in t)!Nr(rh,n)&&Nr(t,n)&&Ua(s,n);for(;e.length>r;)Nr(t,n=e[r++])&&(~ih(s,n)||Ua(s,n));return s},Co=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ah=sh,nh=Co,oh=Object.keys||function(e){return ah(e,nh)},lh=Ue,uh=fo,dh=dt,ch=Xe,hh=si,fh=oh;No.f=lh&&!uh?Object.defineProperties:function(e,t){ch(e);for(var r=hh(t),s=fh(t),n=s.length,o=0,l;n>o;)dh.f(e,l=s[o++],r[l]);return e};var ph=ct,Do=ph("document","documentElement"),mh=Xe,vh=No,ja=Co,Sh=Us,bh=Do,gh=Ds,yh=Fs,Ha=">",Ga="<",Ss="prototype",bs="script",Oo=yh("IE_PROTO"),Cr=function(){},Lo=function(i){return Ga+bs+Ha+i+Ga+"/"+bs+Ha},qa=function(i){i.write(Lo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Th=function(){var i=gh("iframe"),e="java"+bs+":",t;return i.style.display="none",bh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Lo("document.F=Object")),t.close(),t.F},yi,Mi=function(){try{yi=new ActiveXObject("htmlfile")}catch(e){}Mi=typeof document!="undefined"?document.domain&&yi?qa(yi):Th():qa(yi);for(var i=ja.length;i--;)delete Mi[Ss][ja[i]];return Mi()};Sh[Oo]=!0;var xo=Object.create||function(e,t){var r;return e!==null?(Cr[Ss]=mh(e),r=new Cr,Cr[Ss]=null,r[Oo]=e):r=Mi(),t===void 0?r:vh.f(r,t)},Eh=ye,$h=!Eh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Ph=je,kh=se,_h=Ms,wh=Fs,Ah=$h,Ya=wh("IE_PROTO"),gs=Object,Rh=gs.prototype,Bo=Ah?gs.getPrototypeOf:function(i){var e=_h(i);if(Ph(e,Ya))return e[Ya];var t=e.constructor;return kh(t)&&e instanceof t?t.prototype:e instanceof gs?Rh:null},Ih=ai,Ys=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Ih(i,e,t),i},Nh=ye,Ch=se,Dh=Ke,Oh=xo,za=Bo,Lh=Ys,xh=pe,ys=xh("iterator"),Mo=!1,Ve,Dr,Or;[].keys&&(Or=[].keys(),"next"in Or?(Dr=za(za(Or)),Dr!==Object.prototype&&(Ve=Dr)):Mo=!0);var Bh=!Dh(Ve)||Nh(function(){var i={};return Ve[ys].call(i)!==i});Bh?Ve={}:Ve=Oh(Ve);Ch(Ve[ys])||Lh(Ve,ys,function(){return this});var Vo={IteratorPrototype:Ve,BUGGY_SAFARI_ITERATORS:Mo},Mh=pe,Vh=Mh("toStringTag"),Fo={};Fo[Vh]="z";var zs=String(Fo)==="[object z]",Fh=zs,Uh=se,Vi=tr,jh=pe,Hh=jh("toStringTag"),Gh=Object,qh=Vi(function(){return arguments}())=="Arguments",Yh=function(i,e){try{return i[e]}catch(t){}},or=Fh?Vi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Yh(e=Gh(i),Hh))=="string"?t:qh?Vi(e):(r=Vi(e))=="Object"&&Uh(e.callee)?"Arguments":r},zh=zs,Wh=or,Qh=zh?{}.toString:function(){return"[object "+Wh(this)+"]"},Jh=zs,Kh=dt.f,Xh=ai,Zh=je,ef=Qh,tf=pe,Wa=tf("toStringTag"),Ws=function(i,e,t,r){if(i){var s=t?i:i.prototype;Zh(s,Wa)||Kh(s,Wa,{configurable:!0,value:e}),r&&!Jh&&Xh(s,"toString",ef)}},rf=Vo.IteratorPrototype,sf=xo,af=ar,nf=Ws,of=Ct,lf=function(){return this},uf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=sf(rf,{next:af(+!r,t)}),nf(i,s,!1,!0),of[s]=lf,i},df=De,cf=Pe,Uo=Bc,hf=uf,ff=Bo,pf=Ws,Qa=Ys,mf=pe,Ja=Ct,jo=Vo,vf=Uo.PROPER;Uo.CONFIGURABLE;jo.IteratorPrototype;var Ti=jo.BUGGY_SAFARI_ITERATORS,Lr=mf("iterator"),Ka="keys",Ei="values",Xa="entries",Sf=function(){return this},bf=function(i,e,t,r,s,n,o){hf(t,e,r);var l=function(b){if(b===s&&f)return f;if(!Ti&&b in c)return c[b];switch(b){case Ka:return function(){return new t(this,b)};case Ei:return function(){return new t(this,b)};case Xa:return function(){return new t(this,b)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Lr]||c["@@iterator"]||s&&c[s],f=!Ti&&h||l(s),p=e=="Array"&&c.entries||h,v,m,S;if(p&&(v=ff(p.call(new i)),v!==Object.prototype&&v.next&&(pf(v,d,!0,!0),Ja[d]=Sf)),vf&&s==Ei&&h&&h.name!==Ei&&(u=!0,f=function(){return cf(h,this)}),s)if(m={values:l(Ei),keys:n?f:l(Ka),entries:l(Xa)},o)for(S in m)(Ti||u||!(S in c))&&Qa(c,S,m[S]);else df({target:e,proto:!0,forced:Ti||u},m);return o&&c[Lr]!==f&&Qa(c,Lr,f,{name:s}),Ja[e]=f,m},gf=function(i,e){return{value:i,done:e}},yf=si,Qs=Au,Za=Ct,Ho=Eo,Tf=dt.f,Ef=bf,$i=gf,$f=go,Pf=Ue,Go="Array Iterator",kf=Ho.set,_f=Ho.getterFor(Go);Ef(Array,"Array",function(i,e){kf(this,{type:Go,target:yf(i),index:0,kind:e})},function(){var i=_f(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,$i(void 0,!0)):t=="keys"?$i(r,!1):t=="values"?$i(e[r],!1):$i([r,e[r]],!1)},"values");var en=Za.Arguments=Za.Array;Qs();Qs();Qs();if(!$f&&Pf&&en.name!=="values")try{Tf(en,"name",{value:"values"})}catch(i){}var wf=pe,Af=Ct,Rf=wf("iterator"),If=Array.prototype,Nf=function(i){return i!==void 0&&(Af.Array===i||If[Rf]===i)},Cf=or,tn=xs,Df=ir,Of=Ct,Lf=pe,xf=Lf("iterator"),qo=function(i){if(!Df(i))return tn(i,xf)||tn(i,"@@iterator")||Of[Cf(i)]},Bf=Pe,Mf=ht,Vf=Xe,Ff=sr,Uf=qo,jf=TypeError,Hf=function(i,e){var t=arguments.length<2?Uf(i):e;if(Mf(t))return Vf(Bf(t,i));throw jf(Ff(i)+" is not iterable")},Gf=Pe,rn=Xe,qf=xs,Yf=function(i,e,t){var r,s;rn(i);try{if(r=qf(i,"return"),!r){if(e==="throw")throw t;return t}r=Gf(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return rn(r),t},zf=nr,Wf=Pe,Qf=Xe,Jf=sr,Kf=Nf,Xf=qs,sn=Ls,Zf=Hf,ep=qo,an=Yf,tp=TypeError,Fi=function(i,e){this.stopped=i,this.result=e},nn=Fi.prototype,Js=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=zf(e,r),u,c,h,f,p,v,m,S=function(g){return u&&an(u,"normal",g),new Fi(!0,g)},b=function(g){return s?(Qf(g),l?d(g[0],g[1],S):d(g[0],g[1])):l?d(g,S):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=ep(i),!c)throw tp(Jf(i)+" is not iterable");if(Kf(c)){for(h=0,f=Xf(i);f>h;h++)if(p=b(i[h]),p&&sn(nn,p))return p;return new Fi(!1)}u=Zf(i,c)}for(v=n?i.next:u.next;!(m=Wf(v,u)).done;){try{p=b(m.value)}catch(g){an(u,"throw",g)}if(typeof p=="object"&&p&&sn(nn,p))return p}return new Fi(!1)},ip=Vs,rp=dt,sp=ar,ap=function(i,e,t){var r=ip(e);r in i?rp.f(i,r,sp(0,t)):i[r]=t},np=De,op=Js,lp=ap;np({target:"Object",stat:!0},{fromEntries:function(e){var t={};return op(e,function(r,s){lp(t,r,s)},{AS_ENTRIES:!0}),t}});var up=Os,dp=up.Object.fromEntries,cp={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},hp=cp,fp=le,pp=or,mp=ai,on=Ct,vp=pe,ln=vp("toStringTag");for(var xr in hp){var un=fp[xr],Br=un&&un.prototype;Br&&pp(Br)!==ln&&mp(Br,ln,xr),on[xr]=on.Array}var Sp=dp,bp=Sp,gp=bp,yp=gp,oi=yp,Tp=tr,lr=typeof process!="undefined"&&Tp(process)=="process",Ep=ct,$p=dt,Pp=pe,kp=Ue,dn=Pp("species"),_p=function(i){var e=Ep(i),t=$p.f;kp&&e&&!e[dn]&&t(e,dn,{configurable:!0,get:function(){return this}})},wp=Ls,Ap=TypeError,Rp=function(i,e){if(wp(e,i))return i;throw Ap("Incorrect invocation")},Ip=Ce,Np=se,Ts=Bs,Cp=Ip(Function.toString);Np(Ts.inspectSource)||(Ts.inspectSource=function(i){return Cp(i)});var Yo=Ts.inspectSource,Dp=Ce,Op=ye,zo=se,Lp=or,xp=ct,Bp=Yo,Wo=function(){},Mp=[],Qo=xp("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,Vp=Dp(Ks.exec),Fp=!Ks.exec(Wo),Yt=function(e){if(!zo(e))return!1;try{return Qo(Wo,Mp,e),!0}catch(t){return!1}},Jo=function(e){if(!zo(e))return!1;switch(Lp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Fp||!!Vp(Ks,Bp(e))}catch(t){return!0}};Jo.sham=!0;var Up=!Qo||Op(function(){var i;return Yt(Yt.call)||!Yt(Object)||!Yt(function(){i=!0})||i})?Jo:Yt,jp=Up,Hp=sr,Gp=TypeError,qp=function(i){if(jp(i))return i;throw Gp(Hp(i)+" is not a constructor")},cn=Xe,Yp=qp,zp=ir,Wp=pe,Qp=Wp("species"),Ko=function(i,e){var t=cn(i).constructor,r;return t===void 0||zp(r=cn(t)[Qp])?e:Yp(r)},Jp=Ce,Kp=Jp([].slice),Xp=TypeError,Zp=function(i,e){if(i<e)throw Xp("Not enough arguments");return i},em=rr,Xo=/(?:ipad|iphone|ipod).*applewebkit/i.test(em),fe=le,tm=Po,im=nr,hn=se,rm=je,Zo=ye,fn=Do,sm=Kp,pn=Ds,am=Zp,nm=Xo,om=lr,Es=fe.setImmediate,$s=fe.clearImmediate,lm=fe.process,Mr=fe.Dispatch,um=fe.Function,mn=fe.MessageChannel,dm=fe.String,Vr=0,Kt={},vn="onreadystatechange",ri,nt,Fr,Ur;Zo(function(){ri=fe.location});var Xs=function(i){if(rm(Kt,i)){var e=Kt[i];delete Kt[i],e()}},jr=function(i){return function(){Xs(i)}},Sn=function(i){Xs(i.data)},bn=function(i){fe.postMessage(dm(i),ri.protocol+"//"+ri.host)};(!Es||!$s)&&(Es=function(e){am(arguments.length,1);var t=hn(e)?e:um(e),r=sm(arguments,1);return Kt[++Vr]=function(){tm(t,void 0,r)},nt(Vr),Vr},$s=function(e){delete Kt[e]},om?nt=function(i){lm.nextTick(jr(i))}:Mr&&Mr.now?nt=function(i){Mr.now(jr(i))}:mn&&!nm?(Fr=new mn,Ur=Fr.port2,Fr.port1.onmessage=Sn,nt=im(Ur.postMessage,Ur)):fe.addEventListener&&hn(fe.postMessage)&&!fe.importScripts&&ri&&ri.protocol!=="file:"&&!Zo(bn)?(nt=bn,fe.addEventListener("message",Sn,!1)):vn in pn("script")?nt=function(i){fn.appendChild(pn("script"))[vn]=function(){fn.removeChild(this),Xs(i)}}:nt=function(i){setTimeout(jr(i),0)});var el={set:Es,clear:$s},tl=function(){this.head=null,this.tail=null};tl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var il=tl,cm=rr,hm=/ipad|iphone|ipod/i.test(cm)&&typeof Pebble!="undefined",fm=rr,pm=/web0s(?!.*chrome)/i.test(fm),ut=le,gn=nr,mm=js.f,Hr=el.set,vm=il,Sm=Xo,bm=hm,gm=pm,Gr=lr,yn=ut.MutationObserver||ut.WebKitMutationObserver,Tn=ut.document,En=ut.process,Pi=ut.Promise,$n=mm(ut,"queueMicrotask"),Ps=$n&&$n.value,yt,qr,Yr,ki,Pn;if(!Ps){var _i=new vm,wi=function(){var i,e;for(Gr&&(i=En.domain)&&i.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&yt(),t}i&&i.enter()};!Sm&&!Gr&&!gm&&yn&&Tn?(qr=!0,Yr=Tn.createTextNode(""),new yn(wi).observe(Yr,{characterData:!0}),yt=function(){Yr.data=qr=!qr}):!bm&&Pi&&Pi.resolve?(ki=Pi.resolve(void 0),ki.constructor=Pi,Pn=gn(ki.then,ki),yt=function(){Pn(wi)}):Gr?yt=function(){En.nextTick(wi)}:(Hr=gn(Hr,ut),yt=function(){Hr(wi)}),Ps=function(i){_i.head||yt(),_i.add(i)}}var ym=Ps,Tm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Zs=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Em=le,Dt=Em.Promise,rl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",$m=rl,Pm=lr,km=!$m&&!Pm&&typeof window=="object"&&typeof document=="object",_m=le,Xt=Dt,wm=se,Am=Ro,Rm=Yo,Im=pe,Nm=km,Cm=rl,zr=mo,kn=Xt&&Xt.prototype,Dm=Im("species"),ks=!1,sl=wm(_m.PromiseRejectionEvent),Om=Am("Promise",function(){var i=Rm(Xt),e=i!==String(Xt);if(!e&&zr===66||!(kn.catch&&kn.finally))return!0;if(!zr||zr<51||!/native code/.test(i)){var t=new Xt(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Dm]=r,ks=t.then(function(){})instanceof r,!ks)return!0}return!e&&(Nm||Cm)&&!sl}),li={CONSTRUCTOR:Om,REJECTION_EVENT:sl,SUBCLASSING:ks},Ot={},_n=ht,Lm=TypeError,xm=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Lm("Bad Promise constructor");e=r,t=s}),this.resolve=_n(e),this.reject=_n(t)};Ot.f=function(i){return new xm(i)};var Bm=De,zi=lr,Je=le,ui=Pe,Mm=Ys,Vm=Ws,Fm=_p,Um=ht,_s=se,jm=Ke,Hm=Rp,Gm=Ko,al=el.set,ea=ym,qm=Tm,Ym=Zs,zm=il,nl=Eo,ws=Dt,ta=li,ol=Ot,ur="Promise",ll=ta.CONSTRUCTOR,Wm=ta.REJECTION_EVENT;ta.SUBCLASSING;var Wr=nl.getterFor(ur),Qm=nl.set,Jm=ws&&ws.prototype,Et=ws,Qr=Jm,ul=Je.TypeError,As=Je.document,ia=Je.process,Rs=ol.f,Km=Rs,Xm=!!(As&&As.createEvent&&Je.dispatchEvent),dl="unhandledrejection",Zm="rejectionhandled",wn=0,cl=1,ev=2,ra=1,hl=2,Ai,An,tv,fl=function(i){var e;return jm(i)&&_s(e=i.then)?e:!1},pl=function(i,e){var t=e.value,r=e.state==cl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===hl&&rv(e),e.rejection=ra),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(ul("Promise-chain cycle")):(u=fl(d))?ui(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},ml=function(i,e){i.notified||(i.notified=!0,ea(function(){for(var t=i.reactions,r;r=t.get();)pl(r,i);i.notified=!1,e&&!i.rejection&&iv(i)}))},vl=function(i,e,t){var r,s;Xm?(r=As.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Wm&&(s=Je["on"+i])?s(r):i===dl&&qm("Unhandled promise rejection",t)},iv=function(i){ui(al,Je,function(){var e=i.facade,t=i.value,r=Rn(i),s;if(r&&(s=Ym(function(){zi?ia.emit("unhandledRejection",t,e):vl(dl,e,t)}),i.rejection=zi||Rn(i)?hl:ra,s.error))throw s.value})},Rn=function(i){return i.rejection!==ra&&!i.parent},rv=function(i){ui(al,Je,function(){var e=i.facade;zi?ia.emit("rejectionHandled",e):vl(Zm,e,i.value)})},$t=function(i,e,t){return function(r){i(e,r,t)}},kt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ev,ml(i,!0))},Is=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ul("Promise can't be resolved itself");var r=fl(e);r?ea(function(){var s={done:!1};try{ui(r,e,$t(Is,s,i),$t(kt,s,i))}catch(n){kt(s,n,i)}}):(i.value=e,i.state=cl,ml(i,!1))}catch(s){kt({done:!1},s,i)}}};ll&&(Et=function(e){Hm(this,Qr),Um(e),ui(Ai,this);var t=Wr(this);try{e($t(Is,t),$t(kt,t))}catch(r){kt(t,r)}},Qr=Et.prototype,Ai=function(e){Qm(this,{type:ur,done:!1,notified:!1,parent:!1,reactions:new zm,rejection:!1,state:wn,value:void 0})},Ai.prototype=Mm(Qr,"then",function(e,t){var r=Wr(this),s=Rs(Gm(this,Et));return r.parent=!0,s.ok=_s(e)?e:!0,s.fail=_s(t)&&t,s.domain=zi?ia.domain:void 0,r.state==wn?r.reactions.add(s):ea(function(){pl(s,r)}),s.promise}),An=function(){var i=new Ai,e=Wr(i);this.promise=i,this.resolve=$t(Is,e),this.reject=$t(kt,e)},ol.f=Rs=function(i){return i===Et||i===tv?new An(i):Km(i)});Bm({global:!0,constructor:!0,wrap:!0,forced:ll},{Promise:Et});Vm(Et,ur,!1,!0);Fm(ur);var sv=pe,Sl=sv("iterator"),bl=!1;try{var av=0,In={next:function(){return{done:!!av++}},return:function(){bl=!0}};In[Sl]=function(){return this},Array.from(In,function(){throw 2})}catch(i){}var nv=function(i,e){if(!e&&!bl)return!1;var t=!1;try{var r={};r[Sl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},ov=Dt,lv=nv,uv=li.CONSTRUCTOR,gl=uv||!lv(function(i){ov.all(i).then(void 0,function(){})}),dv=De,cv=Pe,hv=ht,fv=Ot,pv=Zs,mv=Js,vv=gl;dv({target:"Promise",stat:!0,forced:vv},{all:function(e){var t=this,r=fv.f(t),s=r.resolve,n=r.reject,o=pv(function(){var l=hv(t.resolve),d=[],u=0,c=1;mv(e,function(h){var f=u++,p=!1;c++,cv(l,t,h).then(function(v){p||(p=!0,d[f]=v,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var Sv=De,bv=li.CONSTRUCTOR,Nn=Dt;Nn&&Nn.prototype;Sv({target:"Promise",proto:!0,forced:bv,real:!0},{catch:function(i){return this.then(void 0,i)}});var gv=De,yv=Pe,Tv=ht,Ev=Ot,$v=Zs,Pv=Js,kv=gl;gv({target:"Promise",stat:!0,forced:kv},{race:function(e){var t=this,r=Ev.f(t),s=r.reject,n=$v(function(){var o=Tv(t.resolve);Pv(e,function(l){yv(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var _v=De,wv=Pe,Av=Ot,Rv=li.CONSTRUCTOR;_v({target:"Promise",stat:!0,forced:Rv},{reject:function(e){var t=Av.f(this);return wv(t.reject,void 0,e),t.promise}});var Iv=Xe,Nv=Ke,Cv=Ot,yl=function(i,e){if(Iv(i),Nv(e)&&e.constructor===i)return e;var t=Cv.f(i),r=t.resolve;return r(e),t.promise},Dv=De,Ov=ct,Lv=go,xv=Dt,Bv=li.CONSTRUCTOR,Mv=yl,Vv=Ov("Promise"),Fv=!Bv;Dv({target:"Promise",stat:!0,forced:Lv},{resolve:function(e){return Mv(Fv&&this===Vv?xv:this,e)}});var Uv=De,Ns=Dt,jv=ye,Hv=ct,Gv=se,qv=Ko,Cn=yl,Yv=Ns&&Ns.prototype,zv=!!Ns&&jv(function(){Yv.finally.call({then:function(){}},function(){})});Uv({target:"Promise",proto:!0,real:!0,forced:zv},{finally:function(i){var e=qv(this,Hv("Promise")),t=Gv(i);return this.then(t?function(r){return Cn(e,i()).then(function(){return r})}:i,t?function(r){return Cn(e,i()).then(function(){throw r})}:i)}});var Wv=ct,Tl=Wv,Qv=Tl,Jv=Qv("Promise","finally"),Kv=Jv,Xv=Kv,Zv=Xv,eS=Zv,dr=eS,_t;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(_t||(_t={}));var At=(i,e=0,t=_t.OFFSET_P)=>{switch(t){case _t.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case _t.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},P=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const $e={[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}},Ui=(i,e)=>$e[i].height>$e[e].height,tS=(i,e)=>$e[i].height>=$e[e].height,Zt=(i,e)=>$e[i].height<$e[e].height,iS=(i,e)=>$e[i].height<=$e[e].height,rS=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Zt(e,t)?1:-1)[0],sS=Object.keys($e).sort((i,e)=>Zt(i,e)?-1:1),ft=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return sS.find(s=>{const n=$e[s];return n.width>=r&&n.height>=t})},aS=i=>$e[i].height,Wi=i=>i===exports.VideoQuality.INVARIANT;class K{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const nS=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var U;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const oS=5,lS=5,uS=500,Dn=7e3;class dS{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new K(U.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&r!==U.STOPPED){this.seek(l.position);return}switch(n){case exports.PlaybackState.PLAYING:{switch(r){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(nS(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(uS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===D.Applying||Math.abs(l-n)>oS)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<lS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(U.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:D.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const e=this.videoState.getTransition();(e==null?void 0:e.to)===U.READY&&this.videoState.setState(U.READY)}handleRemoteStop(){this.videoState.getState()!==U.STOPPED&&this.videoState.setState(U.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=rS(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=r[e];a.assertNonNullable(c),s=At(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===D.Applying||r.state===D.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Dn).subscribe(()=>n(`timeout(${Dn})`)))});dr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function X(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function I(i){return this instanceof I?(this.v=i,this):new I(i)}function Ee(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(v){h(n[0][3],v)}}function d(f){f.value instanceof I?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}class On{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class El extends On{constructor(){super(),this.listeners||On.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let $l=class{constructor(){Object.defineProperty(this,"signal",{value:new El,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&($l.prototype[Symbol.toStringTag]="AbortController",El.prototype[Symbol.toStringTag]="AbortSignal");function Pl(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function cS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Pl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,v)=>{c.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const cr=Pl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),kl=cr?cS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Rt=cr?kl.fetch:window.fetch;cr?kl.Request:window.Request;const ot=cr?$l:window.AbortController,zt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ei{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return X(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=zt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(zt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new ot,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Rt(l,{signal:u}).then(f=>{var p,v,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,b]=f.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,b);const g=S.getReader(),k=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-s+1;c.data=new ArrayBuffer(k);const T=new Uint8Array(c.data),E=({done:w,value:x})=>X(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):x&&(T.set(x,c.loaded),c.loaded+=x.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(E,ei.suppressStreamErrors).catch(h))});g==null||g.read().then(E,ei.suppressStreamErrors).catch(h)},ei.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,v;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of m){const{request:b}=S,[g,k]=zt(b),T=g>=t&&k<=t+s,E=t>=g&&t+s<k,w=n.slice(g-t,Math.min(k-t+1,s));if((T||E)&&(b.requestStartDate=(d=b.requestStartDate)!==null&&d!==void 0?d:new Date,b.firstByteDate=(u=b.firstByteDate)!==null&&u!==void 0?u:new Date,b.bytesLoaded=w.byteLength,b.bytesTotal=r-t),T){b.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(C=>C!==S)),(h=S.success)===null||h===void 0||h.call(S,w,"",e);const x=o?Array.from(o.headers.entries()).map(([C,R])=>`${C}: ${R}`).join(`\r
7
+ `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(b,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,x,[])}else E&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=zt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=zt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Qi{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Qi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Qi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const hS=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new Qi(s,e,r)}}),fS=(i,e)=>{const t=new ei(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return hS(o,t)}}},!0),()=>t.destroy()};var pS=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},mS=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,v,m;const S=oi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(k=>k.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const k=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:k*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const b=(v=S["x-delivery-type"])!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,g=(m={1:!0,0:!1}[S["x-reused"]])!==null&&m!==void 0?m:void 0;r.next(b),s.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,v=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),v(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},It=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},vS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),SS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const Ne=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},pt=(i,e,t)=>Ne(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),He=(i,e,t,r)=>Ne(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),Ze=(i,e,t,r)=>Ne(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),bS=i=>["__",i.language,i.label].join("|"),gS=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Oe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ne(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ne(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:bS(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&gS(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ge=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class sa{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var _l=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Cs=3;class yS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Cs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Cs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var wl=(i,e,t=Cs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const qe=i=>{const e=p=>a.fromEvent(i,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(p=>a.fromEvent(i,p))).pipe(a.map(p=>p.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>wl(i.buffered,i.currentTime))),n=_l()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),l=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),d=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var p;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(p=i.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{i.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=i.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:o,playbackRateState$:l}},aa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var TS=De,ES=Ms,$S=qs,PS=Gs;TS({target:"Array",proto:!0},{at:function(e){var t=ES(this),r=$S(t),s=PS(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var kS=Tl,_S=kS("Array","at"),wS=_S,AS=wS,RS=AS,IS=RS,xe=IS;let na=!1,Be={};const NS=i=>{na=i},CS=()=>{Be={}},DS=i=>{i(Be)},Ri=(i,e)=>{var t;na&&(Be.meta=(t=Be.meta)!==null&&t!==void 0?t:{},Be.meta[i]=e)};class Ie{constructor(e){this.name=e}next(e){var t,r;if(!na)return;Be.series=(t=Be.series)!==null&&t!==void 0?t:{};const s=(r=Be.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Be.series[this.name]=s}}const OS=new Ie("best_bitrate"),LS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class xS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const di=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const v=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*r.containerSizeFactor,height:e.height*v*r.containerSizeFactor},S=m&&ft(m),b=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Wi(N.quality)).sort((N,A)=>Ui(N.quality,A.quality)?-1:1),k=(h=xe(g,-1))===null||h===void 0?void 0:h.quality,T=(f=xe(g,0))===null||f===void 0?void 0:f.quality,E=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&Zt(s.max,s.min)||a.isNonNullable(s.min)&&T&&Ui(s.min,T)||a.isNonNullable(s.max)&&k&&Zt(s.max,k),w=b*LS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C=g.filter(N=>{const A=S?Zt(N.quality,S):!0,B=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,F=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Wi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&Ui(N.quality,d.quality),Y=E||(a.isNullable(s.max)||iS(N.quality,s.max))&&(a.isNullable(s.min)||tS(N.quality,s.min));return A&&B&&!F&&Y})[0];C&&C.bitrate&&OS.next(C.bitrate);const R=(p=C!=null?C:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],V=R&&u&&u.history[R.id]&&a.now()-u.history[R.id]<=r.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!V&&u.recordSelection(R),V&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(R),R};var de=i=>new URL(i).hostname;const BS=300,Ji=(i,e=BS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(uu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),MS=5e3,Wt={};var j;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class VS{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(j.DOWNLOADING_LIB),this.textTracksManager=new Oe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new sa,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===j.DOWNLOADING_LIB||t===j.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&t!==j.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case j.STOPPED:break;case j.PLAYING:case j.PAUSED:case j.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case j.PLAYING:break;case j.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case j.READY:this.play();break;case j.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case j.PLAYING:this.pause(),this.liveOffset.pause();break;case j.PAUSED:break;case j.READY:this.videoState.setState(j.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case j.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),MS);dr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Wt.MediaPlayer=s.MediaPlayer,Wt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Wt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Wt.Debug,"dashjs not loaded"),this.player=Wt.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?aa(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=fS(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&&SS(this.player),pS(this.player),this.params.tuning.requestQuick&&vS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,S)=>this.subscription.add(m.subscribe(S,r));s(Ji(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(m=>{const S=typeof m.error=="object"?m.error.code:m.error,b=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:b}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===j.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{var m,S;const b=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===b))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(a.isNullable(m))return;const b=(S=this.videoTracks.find(({track:g})=>g.id===m))===null||S===void 0?void 0:S.bitrateInfo;b&&this.player.setQualityFor("video",b.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:r}))},r)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>{var m,S,b;return(b=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||b===void 0?void 0:b.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var b,g;const k=this.player.getDashMetrics(),T=k.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),E=(b=k.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[T])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(de(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:b}}})=>{this.isLive$.next(S),this.availableFrom$.next(b.getTime()),S||e.duration$.next(m),this.videoTracks=[];const g=this.player.getQualityFor("video");let k;for(const T of this.player.getBitrateInfoListFor("video")){const E=T.qualityIndex.toString(10),w=ft(T),x=T.bitrate/1e3,C={width:T.width,height:T.height},R=this.frameRatesByFrameHeight[T.height];if(w){const V={id:E,quality:w,bitrate:x,size:C,fps:R};this.videoTracks.push({track:V,bitrateInfo:T}),T.qualityIndex===g&&(k=V)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:T})=>T)),k&&e.currentVideoTrack$.next(k),this.videoState.setState(j.STREAM_INITIALIZED),this.videoState.startTransitionTo(j.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),b=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(b,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=di(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),b=this.videoTracks.find(({track:g})=>g===S);b!=null&&b.bitrateInfo&&this.player.setQualityFor("video",b==null?void 0:b.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>wl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(j.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(j.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(j.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===j.READY&&this.videoState.setState(j.READY)}),s(this.isLive$,e.isLive$),s(Ji(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=mS(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:S})=>{const b=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:b}}})}),s(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(pt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:v}=qe(this.video);this.subscription.add(He(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Ze(this.video,t.playbackRate,v,r))}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(j.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(j.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=At(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,_t.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(j.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(j.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(r){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var ci=i=>{switch(i){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}},et=i=>X(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function Al(i){return oe()-i}function Ln(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function FS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function ji(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",v=7e3,m=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const A=Al(c);let B;if(A<m){B=m-A,setTimeout(S,B);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,w()};const b=A=>(n=A,N),g=A=>(h=A,N),k=()=>(p="json",N),T=()=>{if(!d){if(--u>=0){S(),r&&r();return}d=!0,h&&h(),t&&t()}},E=A=>(f=A,N),w=()=>{c=oe(),o=new s,o.open("get",i);let A=0,B,F=0;const Y=()=>(a.assertNonNullable(c),Math.max(c,Math.max(B||0,F||0)));if(n&&o.addEventListener("progress",$=>{const O=oe();n.updateChunk&&$.loaded>A&&(n.updateChunk(Y(),$.loaded-A),A=$.loaded,B=O)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const O=o.response.byteLength-A;O&&n.updateChunk&&n.updateChunk(Y(),O)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(F=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:b,withParallel:E,withJSONResponse:k,withRetryCount:A=>(u=A,N),withRetryInterval:(A,B)=>(a.isNonNullable(A)&&(m=A),a.isNonNullable(B)&&(v=B),N),withTimeout:A=>(l=A,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const US=100,jS=2e3,HS=500;let GS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-HS;if(t-e>jS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>US&&(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 qS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=oe(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=oe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ji(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=oe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Ni=3,YS=300,zS=2e3,WS=6e4,QS=10,JS=1,KS=500;class XS{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new GS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ln(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Ln(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{FS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new qS(Ni,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,w)=>{d&&d.abort(),d=ji(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ni).withFinally(()=>{d=null}).send()},p=(T,E,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=T=>{const E=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),r.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency)v(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const w=oe()-6e4;let x=0;for(let R=0;R<this.bufferStates.length;R++){const V=this.bufferStates[R];T=Math.min(T,V.buf),V.ts<w&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${T} drop=${x} jitter=${this.sourceJitter}`);let C=T-JS;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?v(1.15):C>1?v(1.1):C>.3?v(1.01):v(1)}},b=T=>{let E;const w=()=>E&&E.start?E.start.length:0,x=$=>E.start[$]/1e3,C=$=>E.dur[$]/1e3,R=$=>E.fragIndex+$,V=($,O)=>({chunkIdx:R($),startTS:x($),dur:C($),discontinuity:O}),N=()=>{let $=0;if(E&&E.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=O;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(te-=E.dur[ie],!(te<=0));--ie);$=Math.min(ie,E.dur.length-1-Q),$=Math.max($,0)}return V($,!0)},A=$=>{const O=w();if(!(O<=0)){if(a.isNonNullable($)){for(let Q=0;Q<O;Q++)if(x(Q)>$)return V(Q)}return N()}},B=$=>{const O=w(),Q=$?$.chunkIdx+1:0,te=Q-E.fragIndex;if(!(O<=0)){if(!$||te<0||te-O>QS)return t(`Resync: offset=${te} bChunks=${O} chunk=`+JSON.stringify($)),N();if(!(te>=O))return V(Q-E.fragIndex,!1)}},F=($,O,Q)=>{u&&u.abort(),u=ji(this.urlResolver.resolve($,!0,this.lowLatency),O,Q,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,O)=>{F(T,Q=>{if(!h())return;E=Q;const te=Boolean(E.lowLatency);te!==this.lowLatency&&m(te);let ie=0;for(let ce=0;ce<E.dur.length;++ce)ie+=E.dur[ce];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),s({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(A(O))},()=>this._handleNetworkError())},nextChunk:B}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:w}=this.params;let x=b(e.jidxUrl),C,R,V,N,A=0,B,F,Y;const $=()=>{B&&(clearTimeout(B),B=void 0);const H=Math.max(KS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=A+H,ue=oe(),me=Math.min(1e4,ae-ue);A=ue;const tt=()=>{u||h()&&x.seek(()=>{h()&&(A=oe(),O(),$())})};me>0?B=window.setTimeout(()=>{this.paused?$():tt()},me):tt()},O=()=>{let H;for(;H=x.nextChunk(N);)N=H,ke(H);const ae=x.nextChunk(V);if(ae){if(V&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}ce(ae)}else $()},Q=(H,ae)=>{if(!h()||!this.sourceBuffer)return;let ue,me,tt;const _e=Ye=>{window.setTimeout(()=>{h()&&Q(H,ae)},Ye)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),_e(100);else{const Ye=oe(),it=E.currentTime;!this.paused&&E.buffered.length>1&&F===it&&Ye-Y>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),F!==it&&(F=it,Y=Ye);const xt=this._getBufferSizeSec();if(xt>30)w(`Buffered ${xt} seconds; delaying appendBuffer`),_e(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:Ye,buf:xt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(mt){if(mt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(ue=this.sourceBuffer.buffered.start(0),me=it,me-ue>4&&this.sourceBuffer.remove(ue,me-3)),_e(1e3);else throw mt}}},te=()=>{R&&C&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(V)]),Q(R,function(){R=null,O()}))},ie=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),ce=H=>{h()&&p(ie(H),(ae,ue)=>{if(h()){if(ue/=1e3,R=ae,V=H,o=H.startTS,ue){const me=Math.min(10,H.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}te()}},()=>this._handleNetworkError())},ke=H=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(H),!1)))},Lt=H=>{h()&&(e.cachedHeader=H,Q(H,()=>{C=!0,te()}))};n=!0,x.seek(H=>{if(h()){if(A=oe(),!H){$();return}N=H,!a.isNullable(T)||H.startTS>T?ce(H):(V=H,O())}},T),e.cachedHeader?Lt(e.cachedHeader):f(e.headerUrl,Lt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=oe();if(this.chunkRateEstimator.addInterval(f,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Al(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=ji(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Ni).withRetryInterval(YS,zS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;et(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},WS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var L;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const ZS=[L.PAUSED,L.PLAYING,L.READY],eb=[L.PAUSED,L.PLAYING,L.READY];class tb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(L.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Oe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new sa,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=ci(h.name))!==null&&o!==void 0?o:ft(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:v,size:m};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===L.MANIFEST_READY&&this.videoState.setState(L.MANIFEST_READY);break}case"qualitySwitch":{const u=s.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(L.STOPPED));return}if(!o){if(eb.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&ZS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_READY),this.dash.attachSource(At(this.params.source.url));return;case L.MANIFEST_READY:this.videoState.startTransitionTo(L.READY),this.prepare();break;case L.READY:l===exports.PlaybackState.PAUSED?this.videoState.setState(L.PAUSED):l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(L.PAUSED)}));return;case L.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(L.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case L.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.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(L.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Ge(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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=qe(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===L.READY&&this.videoState.setState(L.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(L.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(pt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&aS(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case L.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case L.MANIFEST_READY:case L.READY:break;case L.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case L.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new XS({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,r,s,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=di(l.map(({track:f})=>f),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.dash.reinit(At(this.params.source.url,r))}}var Rl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},wt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const ib=i=>{const e=document.createElement("a");return e.href=i,e.origin},rb=i=>{const e=document.createElement("a");return e.href=i,e.host};class Il{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=oi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(rb(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ki{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{s(Ki._str2ua(m.substr(d))),d=m.length};let v=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(v=It(v)),this._lastXhr=new Il(v,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const S=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:S,speed:8*m.length/(S/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,S,b)=>this._params.onError(m,S,b))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ki._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class sb{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=It(r)),new Il(r,t,s=>{this.attachManifest(s,t,ib(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,v,m,S,b,g,k,T,E,w,x,C,R,V,N,A;const B=u.getElementsByTagName("SegmentBase")[0],F=B&&o(B,"indexRange").split("-"),Y=B&&B.getElementsByTagName("Initialization")[0],$=Y&&o(Y,"range").split("-");if(!$||!F){const ke=u.parentElement;if((ke==null?void 0:ke.getAttribute("contentType"))==="text"){const Lt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,H=(r?r+"/":"")+((v=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),ae=(m=ke.getAttribute("lang"))!==null&&m!==void 0?m:void 0;H&&d.push({id:Lt,url:H,language:ae})}return}const O=.1,Q=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),te=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const ce=(g=(b=u.attributes.getNamedItem("frameRate"))===null||b===void 0?void 0:b.value)!==null&&g!==void 0?g:void 0;ie=ce?aa(ce):void 0,l.push({width:Number((k=u.attributes.getNamedItem("width"))===null||k===void 0?void 0:k.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:Q,baseURL:te,failoverHosts:t,indexFrom:Number(F[0]),indexTo:Number(F[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&w!==void 0?w:void 0,mimeType:(C=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&C!==void 0?C:void 0,fps:ie,bufferSize:O*Q/8,bufferLength:O,name:(V=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&V!==void 0?V:void 0,id:(A=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.value)!==null&&A!==void 0?A:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),v=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:v/l,fromOffset:u,toOffset:p-1}),u=p,d=v}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const r=new t;let s,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ki({mediaSource:r,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const ab=[M.PAUSED,M.PLAYING];class nb{constructor(e){this.videoState=new K(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&ci(l.name))!==null&&n!==void 0?n:ft(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.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(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===D.Requested&&ab.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new yS(this.video),this.dash=new sb({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,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=qe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==D.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(Ji(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.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$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),S=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let b;if(!S&&a.isNonNullable(p))b=p;else{const g=wt(this.video.buffered,this.video.currentTime*1e3),k=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(g/k,1);b=(d=di(h.map(({track:E})=>E),{container:m,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:T,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:E})=>E===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(b)?(u=h.find(({track:g})=>g.id===b))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=wt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(de(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Rl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}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 a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var Xi;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Xi||(Xi={}));var be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(be||(be={}));var G;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(G||(G={}));var Nt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Nt||(Nt={}));var xn=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const ob=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},lb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Bn=lb?ob:window.requestIdleCallback;var Jr,Kr;let Nl=!1;try{Nl=_l()&&parseInt((Kr=(Jr=navigator.userAgent.match(/Version\/(\d+)/))===null||Jr===void 0?void 0:Jr[1])!==null&&Kr!==void 0?Kr:"",10)<16}catch(i){console.error(i)}class ub{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return X(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return X(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return X(this,void 0,void 0,function*(){return new Promise(t=>{let r;Nl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var Mn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Cl=new TextDecoder("ascii"),Dl=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Cl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},db=i=>Cl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",cb=i=>{const e=Dl(i),t=[];let r=0;const s=()=>{const p=e.contents.getUint32(r);return r+=4,p};if((s()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");s();const l=s(),d=s(),u=s(),c=s()&4294967295;let h=d/l*1e3,f=i.byteOffset+i.byteLength+u;for(let p=0;p<c;p++){const v=s(),m=v>>>31,S=v<<1>>>1,b=s();if(s(),m!==0)throw new Error("Unsupported multilevel sidx");const g=b/l*1e3;t.push({status:G.NONE,time:{from:h,to:h+g},byte:{from:f,to:f+S-1}}),h+=g,f+=S}return t},hb=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=Dl(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},fb={validateData:db,parseInit:()=>null,getIndexRange:()=>{},parseSegments:cb,parseFeedableSegmentChunk:hb};var y;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(y||(y={}));var _;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(_||(_={}));const Vn={[y.EBML]:{type:_.Master},[y.EBMLVersion]:{type:_.UnsignedInteger},[y.EBMLReadVersion]:{type:_.UnsignedInteger},[y.EBMLMaxIDLength]:{type:_.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[y.DocType]:{type:_.String},[y.DocTypeVersion]:{type:_.UnsignedInteger},[y.DocTypeReadVersion]:{type:_.UnsignedInteger},[y.Void]:{type:_.Binary},[y.Segment]:{type:_.Master},[y.SeekHead]:{type:_.Master},[y.Seek]:{type:_.Master},[y.SeekID]:{type:_.Binary},[y.SeekPosition]:{type:_.UnsignedInteger},[y.Info]:{type:_.Master},[y.TimestampScale]:{type:_.UnsignedInteger},[y.Duration]:{type:_.Float},[y.Tracks]:{type:_.Master},[y.Chapters]:{type:_.Master},[y.Cluster]:{type:_.Master},[y.Timestamp]:{type:_.UnsignedInteger},[y.SilentTracks]:{type:_.Master},[y.SilentTrackNumber]:{type:_.UnsignedInteger},[y.Position]:{type:_.UnsignedInteger},[y.PrevSize]:{type:_.UnsignedInteger},[y.SimpleBlock]:{type:_.Binary},[y.BlockGroup]:{type:_.Master},[y.EncryptedBlock]:{type:_.Binary},[y.Attachments]:{type:_.Master},[y.Tags]:{type:_.Master},[y.Cues]:{type:_.Master},[y.CuePoint]:{type:_.Master},[y.CueTime]:{type:_.UnsignedInteger},[y.CueTrackPositions]:{type:_.Master},[y.CueTrack]:{type:_.UnsignedInteger},[y.CueClusterPosition]:{type:_.UnsignedInteger},[y.CueRelativePosition]:{type:_.UnsignedInteger},[y.CueDuration]:{type:_.UnsignedInteger},[y.CueBlockNumber]:{type:_.UnsignedInteger},[y.CueCodecState]:{type:_.UnsignedInteger},[y.CueReference]:{type:_.Master},[y.CueRefTime]:{type:_.UnsignedInteger}},Ol=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=Zi(i,t),s=r in Vn,n=s?Vn[r].type:_.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Zi(d),c=t+l;let h;return c+u>i.byteLength?h=new DataView(i.buffer,i.byteOffset+c):h=new DataView(i.buffer,i.byteOffset+c,u),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Zi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},Me=(i,e)=>{switch(e){case _.SignedInteger:return i.getInt8(0);case _.UnsignedInteger:return Zi(i);case _.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(i);case _.UTF8:return new TextDecoder("utf-8").decode(i);case _.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case _.Master:return i;case _.Binary:return i;default:a.assertNever(e)}},hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=Ol(r);if(!e(s))return;s.type===_.Master&&hi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},pb=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=Ol(i);return hi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Me(l,o):n===y.DocType?t=Me(l,o):n===y.DocTypeReadVersion&&(r=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Ll=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],mb=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],vb=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return hi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const v=Me(f,h);u=Zi(v)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Me(f,h):c===y.Duration?s=Me(f,h):c===y.SeekPosition&&u===y.Cues?d=Me(f,h):n&&o&&Ll.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},Sb=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bb=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return hi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Me(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&Ll.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},gb=i=>{let e=0,t=!1;try{hi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):mb.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},yb={validateData:pb,parseInit:vb,getIndexRange:Sb,parseSegments:bb,parseFeedableSegmentChunk:gb};class Fn{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ot,this.destroyAbortController=new ot,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new ub(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,Mn(this.sourceBuffer.buffered));this.bufferLimit=m,this.pruneBuffer(v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield yield I(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield I(void 0);let p=0;for(const v of f)v.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:v.time.from}),p=v.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield I(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield I(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield I(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield I(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield I(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield I(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Nt.MP4:this.containerParser=fb;break;case Nt.WEBM:this.containerParser=yb;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ot,this.abortBuffer()}maintain(e){if(a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=wt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Mn(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),s&&s.status!==G.NONE))return;let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=xe(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.allInitsLoaded&&s&&s.status===G.FED&&!l.length&&wt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=xe(r,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&this.mediaSource.readyState==="open"&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,r){const s=e.findIndex(({status:d,time:{from:u,to:c}})=>d===G.NONE&&(u>r||u<=r&&c>=r)&&c<=r+this.forwardBufferTarget);if(s===-1)return[];if(t!==be.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0;const l=[];for(let d=s;d<n.length&&o<=this.tuning.dash.segmentRequestSize;d++){const u=n[d];if(o+=u.byte.to+1-u.byte.from,u.status===G.NONE||u.status===G.PARTIALLY_EJECTED)l.push(u);else break}return l}loadSegments(e,t,r="auto"){return X(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case be.BYTE_RANGE:{s=t.segmentReference.url,n={from:xe(e,0).byte.from,to:xe(e,-1).byte.to};break}case be.TEMPLATE:{const u=xe(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=G.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Ee(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield I(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=wt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=h=>{this.abortSegment(h.segment)},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=G.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const v of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])v.status===G.FED&&v.time.from===h.segment.time.from&&v.time.to===h.segment.time.to&&(v.status=G.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===be.BYTE_RANGE,v=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o(h);continue}const S=p?f.byte.from-r:0,b=p?f.byte.to-r:e.byteLength,g=S<s,k=b<=s;if(f.status===G.DOWNLOADING&&g&&k){f.status=G.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(v,s-S),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===v?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=G.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(w=>{if(n.aborted)o(h);else if(w)h.fedBytes+=E.byteLength,h.fedBytes===v&&l(h);else{if(h.feedingBytes<v)return;o(h)}}))}}}abortSegment(e){e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=Bn(()=>dr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return X(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ee(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield I(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e){return X(this,void 0,void 0,function*(){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(t)||this.sourceBuffer.updating)return!1;const r=this.segments.get(this.playingRepresentationId);if(!r)return!1;let s=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;s+=h};for(const u of r){if(u.time.to>=t||s>=e)break;u.status===G.FED&&d(u)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of r){if(u.time.from<t+this.forwardBufferTarget||s>e)break;u.status===G.FED&&d(u)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of r)if(f.status===G.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(h)){n=c,o=h;break}}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Bn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==G.FED&&n!==G.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.some(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u?s.status=G.PARTIALLY_EJECTED:s.status=G.NONE)}}}var Pt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pt||(Pt={}));class Tb{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new ot,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Ee(this,arguments,function*(){let n=s;this.requestQuic&&(n=It(n));const o=yield yield I(Rt(n,{signal:this.abortAllController.signal}).catch(Qt));return o?(this.onHeadersReceived(o.headers),yield I(o.text())):yield I(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,v;return Ee(this,arguments,function*(){let m=s;const S=new Headers;if(o)switch(n){case Pt.HEADER:{S.append("Range",`${o.from}-${o.to}`);break}case Pt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=It(m));let b=this.abortAllController.signal;if(u){const $=new ot;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(O){Qt(O)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(O){Qt(O)}b=$.signal}const g=a.now(),k=yield yield I(Rt(m,{priority:d,headers:S,signal:b}).catch(Qt)),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-g),!k)return yield I(null);if(!k.ok||!k.body)return yield I(Promise.reject(new Error(`Fetch error ${k.status}: ${k.statusText}`)));this.onHeadersReceived(k.headers);const E=parseInt((f=k.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!E){const $=yield yield I(k.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-T),l==null||l(new DataView($),$.byteLength),yield I($)}if(!l&&!c)return yield I(k.arrayBuffer());const[w,x]=k.body.tee(),C=w.getReader();c&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(x));let R=0;const V=new ArrayBuffer(E),N=new Uint8Array(V),A=new DataView(V);let B=!1;const F=$=>{B=!0,Qt($)},Y=a.abortable(b,function({done:$,value:O}){return Ee(this,arguments,function*(){if(R===0&&this.lastRequestFirstBytes$.next(a.now()-g),b.aborted)return yield I(void 0);$?l==null||l(A,R):O&&(N.set(O,R),R+=O.byteLength,l==null||l(A,R),yield yield I(C==null?void 0:C.read().then(Y,F)))})}.bind(this));return yield yield I(C==null?void 0:C.read().then(Y,F)),yield I(B?null:V)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){return Ee(this,arguments,function*(){if(s.type!==be.BYTE_RANGE)return yield I(null);const{from:l,to:d}=s.initRange;let u=l,c=d,h=!1,f,p;s.indexRange&&(f=s.indexRange.from,p=s.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(p,d))),u=Math.min(u,0);const v=yield yield I(this.fetch(s.url,{range:{from:u,to:c},priority:o,measureThroughput:!1}));if(!v)return yield I(null);const m=new DataView(v,l-u,d-u+1);if(!n.validateData(m))throw new Error("Invalid media file");const S=n.parseInit(m);let b;if(h&&f!==void 0&&p!==void 0)b=new DataView(v,f-u,p-f+1);else{const k=n.getIndexRange(S);if(k){const T=yield yield I(this.fetch(s.url,{range:k,priority:o,measureThroughput:!1}));if(!T)return yield I(null);b=new DataView(T)}}if(!b)throw new ReferenceError("No way to load representation index");const g=n.parseSegments(b,S);return yield I({dataView:new DataView(v),segments:g})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Ee(this,arguments,function*(){if(s.type!==be.TEMPLATE)return yield I(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield I(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield I(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield I({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=Rl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return X(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case be.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case be.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},Un=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Xr=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Eb=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,v,m,S,b,g,k,T,E,w,x,C,R,V,N,A,B,F,Y,$,O,Q,te,ie,ce,ke;const H=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},ue=H.children[0],me=ue.getElementsByTagName("Period")[0],tt=me.children;let _e;const Ye=ue.getAttribute("mediaPresentationDuration"),it=me.getAttribute("duration");if(Ye)_e=Un(Ye);else if(it){const we=Un(it);a.isNonNullable(we)&&(_e=we)}let xt=0;const mt=(r=(t=ue.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],Vl=mt.includes(Xi.WEBM_AS_IN_FFMPEG)||mt.includes(Xi.WEBM_AS_IN_SPEC)?Nt.WEBM:Nt.MP4;for(const we of tt){const fi=we.getAttribute("mimeType"),Fl=we.getAttribute("codecs"),oa=(s=we.getAttribute("contentType"))!==null&&s!==void 0?s:fi==null?void 0:fi.split("/")[0],Ul=(o=(n=we.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],jl=we.querySelectorAll("Representation"),Hl=we.querySelector("SegmentTemplate");if(oa!=="text")for(const ne of jl){const Bt=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:fi,la=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:Fl)!==null&&u!==void 0?u:"",pi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Bt==null?void 0:Bt.split("/")[0])!==null&&h!==void 0?h:oa,Gl=(p=(f=we.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],ql=parseInt((v=ne.getAttribute("width"))!==null&&v!==void 0?v:"",10),ua=parseInt((m=ne.getAttribute("height"))!==null&&m!==void 0?m:"",10),da=parseInt((S=ne.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,ca=(b=ne.getAttribute("frameRate"))!==null&&b!==void 0?b:"",Yl=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,zl=ca?aa(ca):void 0,Wl=(k=ne.getAttribute("id"))!==null&&k!==void 0?k:(xt++).toString(10),Ql=pi==="video"?`${ua}p`:pi==="audio"?`${da}Kbps`:la,Jl=`${Wl}@${Ql}`,Kl=(w=(E=(T=ne.querySelector("BaseURL"))===null||T===void 0?void 0:T.textContent)===null||E===void 0?void 0:E.trim())!==null&&w!==void 0?w:"",ha=new URL(Kl,e).toString(),Xl=[...mt,...Ul,...Gl];let fr;const Zl=ne.querySelector("SegmentBase"),rt=(x=ne.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:Hl;if(Zl){const Mt=(R=(C=ne.querySelector("SegmentBase Initialization"))===null||C===void 0?void 0:C.getAttribute("range"))!==null&&R!==void 0?R:"",[Vt,mr]=Mt.split("-").map(st=>parseInt(st,10)),Ft={from:Vt,to:mr},Ut=(V=ne.querySelector("SegmentBase"))===null||V===void 0?void 0:V.getAttribute("indexRange"),[vr,mi]=Ut?Ut.split("-").map(st=>parseInt(st,10)):[],jt=Ut?{from:vr,to:mi}:void 0;fr={type:be.BYTE_RANGE,url:ha,initRange:Ft,indexRange:jt}}else if(rt){const Mt={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(A=ne.getAttribute("bandwidth"))!==null&&A!==void 0?A:void 0},Vt=parseInt((B=rt.getAttribute("timescale"))!==null&&B!==void 0?B:"",10),mr=(F=rt.getAttribute("initialization"))!==null&&F!==void 0?F:"",Ft=rt.getAttribute("media"),Ut=($=parseInt((Y=rt.getAttribute("startNumber"))!==null&&Y!==void 0?Y:"",10))!==null&&$!==void 0?$:1,vr=Xr(mr,Mt);if(!Ft)throw new ReferenceError("No media attribute in SegmentTemplate");const mi=(O=rt.querySelectorAll("SegmentTimeline S"))!==null&&O!==void 0?O:[],jt=[];if(mi.length){let st=Ut,at=0;for(const Ht of mi){const vt=parseInt((Q=Ht.getAttribute("d"))!==null&&Q!==void 0?Q:"",10)*1e3,Gt=parseInt((te=Ht.getAttribute("r"))!==null&&te!==void 0?te:"",10)||0,qt=(ce=parseInt((ie=Ht.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&ce!==void 0?ce:void 0;for(let fa=0;fa<Gt+1;fa++){const eu=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:st.toString(10),segmentTime:qt.toString(10)})),tu=qt?qt/Vt:at;at+=vt/Vt;const iu=at;st++,jt.push({time:{from:tu,to:iu},url:eu})}}}else if(a.isNonNullable(_e)){const at=parseInt((ke=rt.getAttribute("duration"))!==null&&ke!==void 0?ke:"",10)/Vt*1e3,Ht=Math.ceil(_e/at);let vt=0;for(let Gt=1;Gt<Ht;Gt++){const qt=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:Gt.toString(10),segmentTime:vt.toString(10)}));jt.push({time:{from:vt,to:vt+at},url:qt}),vt+=at}}fr={type:be.TEMPLATE,baseUrl:ha,initUrl:vr,segments:jt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!pi||!Bt)continue;const pr={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[pi];pr&&ae[pr].push({id:Jl,kind:pr,segmentReference:fr,profiles:Xl,duration:_e,bitrate:da,mime:Bt,codecs:la,width:ql,height:ua,fps:zl,quality:Yl})}}return{duration:_e,container:Vl,representations:ae}},$b=["timeupdate","progress","play","seeked","stalled"];var ve;(function(i){i.NONE="none",i.MANIFEST_LOADED="manifest_loaded",i.REPRESENTATION_SELECTED="representation_selected"})(ve||(ve={}));let Pb=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new K(ve.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new ot,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(ve.MANIFEST_LOADED);const s=yield yield I(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield I(null);let n;try{n=Eb(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield I(null);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};return this.manifest=Object.assign(Object.assign({},n),{representations:oi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(ve.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"}),yield I(this.manifest)})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(ve.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Fn(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Fn(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield I(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield I(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield I(this.videoBufferManager.startWith(t)),this.state$.setState(ve.REPRESENTATION_SELECTED),a.assertNonNullable(this.element),this.subscription.add(a.merge(...$b.map(l=>a.fromEvent(this.element,l)),a.fromEvent(window,"online")).subscribe(this.tick,l=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:l})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&xn(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Tb({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}switchRepresentation(e,t){return X(this,void 0,void 0,function*(){const r={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),xn(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));const kb=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?ci(n):void 0)!==null&&o!==void 0?o:ft({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},_b=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=xe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:xe(i,-1)};class wb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(Z.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new xS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===D.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==Z.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.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(Z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}switch(t){case Z.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=Ge(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=qe(this.video),s=d=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:d})},n=(d,u)=>this.subscription.add(d.subscribe(u,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.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(pt(this.video,t.isLooped,s)),this.subscription.add(He(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ze(this.video,t.playbackRate,r.playbackRateState$,s)),n(Ji(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(a.filter(({to:d})=>d===ve.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(Z.READY)}));const o=d=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{var d,u,c,h,f,p,v,m;const S=this.player.state$.getState(),b=this.player.state$.getTransition();if(S===ve.NONE||!this.videoTracks.length)return;const g=S===ve.MANIFEST_LOADED&&!b,k=S===ve.REPRESENTATION_SELECTED&&!b,T=t.autoVideoTrackSwitching.getState(),E=t.videoTrack.getState(),w=(d=this.videoTracks.find(({track:{id:F}})=>F===E))===null||d===void 0?void 0:d.track,x=e.currentVideoTrack$.getValue(),C=wt(this.video.buffered,this.video.currentTime*1e3),R=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,V=Math.min(C/Math.min(R,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),N=Math.max(w&&!T&&(c=(u=this.audioRepresentations.get(w.id))===null||u===void 0?void 0:u.bitrate)!==null&&c!==void 0?c:0,x&&(f=(h=this.audioRepresentations.get(x.id))===null||h===void 0?void 0:h.bitrate)!==null&&f!==void 0?f:0),A=di(this.videoTracks.map(({track:F})=>F),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:N,forwardBufferHealth:V,current:x,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),B=T?A!=null?A:w:w!=null?w:A;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState(T),this.player.setBufferTarget(R)),g){const F=B&&((p=this.videoTracks.find(({track:Y})=>Y===B))===null||p===void 0?void 0:p.representation);a.assertNonNullable(F),this.player.initRepresentations(F.id,(v=this.audioRepresentations.get(F.id))===null||v===void 0?void 0:v.id)}else if(k){const F=B&&((m=this.videoTracks.find(({track:Y})=>Y===B))===null||m===void 0?void 0:m.representation);if(F){const Y=this.audioRepresentations.get(F.id);this.player.switchRepresentation(Se.VIDEO,F.id).catch(o),Y&&this.player.switchRepresentation(Se.AUDIO,Y.id).catch(o)}}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(d=>{var u;return d&&((u=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){return X(this,void 0,void 0,function*(){const e=yield this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((s,n)=>n.bitrate-s.bitrate),r=Array.from(e.representations.video).sort((s,n)=>n.bitrate-s.bitrate);for(const s of r){const n=kb(s);if(n){this.videoTracks.push({track:n,representation:s});const o=_b(t,r,s);o&&this.audioRepresentations.set(s.id,o)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:s})=>s))})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Ab=5e3,Le={};var q;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const Ci=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Rb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(q.INITIALIZING),this.textTracksManager=new Oe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==q.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case q.STOPPED:break;case q.READY:case q.PLAYING:case q.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case q.PLAYING:break;case q.STOPPED:this.prepare();break;case q.READY:case q.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case q.PAUSED:break;case q.STOPPED:this.prepare();break;case q.READY:this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case q.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Ab);dr(import("hls.js").then(s=>{e||(Le.Hls=s.default,Le.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Le.Hls,"hls.js not loaded"),this.hls=new Le.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(q.STOPPED)}subscribe(){a.assertNonNullable(Le.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=qe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),this.subscription.add(pt(this.video,e.isLooped,r)),this.subscription.add(He(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Ci(this.hls,Le.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},r)),n(Ci(this.hls,Le.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:S}=h,b=(p=ci((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:ft({width:m,height:S});if(!b)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,k={id:v.toString(),quality:b,bitrate:h.bitrate/1e3,size:{width:m,height:S},fps:g};return this.trackLevels.set(v,{track:k,level:h}),c.push(k),c},[]))),t.availableVideoTracks$),n(Ci(this.hls,Le.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>de(u))),t.hostname$),this.subscription.add(Ne(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ci(this.hls,Le.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ne(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(q.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return X(this,void 0,void 0,function*(){this.videoState.startTransitionTo(q.PLAYING),(yield et(this.video))||(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(q.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jn="X-Playback-Duration";var Hn=i=>X(void 0,void 0,void 0,function*(){const e=yield Rt(i,{method:"HEAD"});return e.headers.has(jn)?parseInt(e.headers.get(jn),10):void 0});const Ib=i=>{let e=null;if(i.QUALITY&&(e=ci(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=ft({width:t,height:r})}return e!=null?e:null},xl=(i,e=i)=>X(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Rt(i)).text()).split(`
8
+ `),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=oi(u[1].split(",").map(b=>b.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Ib(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let m;if(c.RESOLUTION){const[b,g]=c.RESOLUTION.split("x").map(k=>parseInt(k,10));b&&g&&(m={width:b,height:g})}const S=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:S,bandwidth:p,size:m,fps:v})}return o});var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(z||(z={}));class Nb{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new K(z.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new sa,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){s!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===D.Requested){this.videoState.startTransitionTo(z.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case z.READY:n===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case z.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),xl(At(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===D.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=At(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Hn(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Rt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Hn(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var J;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(J||(J={}));class Cb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(J.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==J.STOPPED&&(this.videoState.startTransitionTo(J.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(J.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&this.seek(u.position),r){case J.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),xl(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===D.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ee||(ee={}));class Db{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(ee.STOPPED),this.trackUrls={},this.textTracksManager=new Oe,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&this.seek(l.position),t){case ee.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===ee.READY&&this.videoState.setState(ee.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const r=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=It(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Gn=["stun:videostun.mycdn.me:80"],Ob=1e3,Lb=3,Zr=()=>null;class xb{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return X(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return X(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Gn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return X(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return X(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return X(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return X(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Ob)}normalizeOptions(e={}){const t={stunServerList:Gn,maxRetryNumber:Lb,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));class Bb{constructor(e){this.videoState=new K(W.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case W.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container),this.liveStreamClient=new xb(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=qe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(He(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case W.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.READY:break;case W.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(W.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class qn{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var Mb=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},es,ts,is,rs,ss,as,Di,ns,Oi,os,Li,ls,xi,us,Bi,ds;const Bl=Mb(),We=document.createElement("video"),ze={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ts=(es=window.SourceBuffer)===null||es===void 0?void 0:es.prototype)===null||ts===void 0?void 0:ts.appendBuffer)),hls:Boolean(((is=We.canPlayType)===null||is===void 0?void 0:is.call(We,"application/x-mpegurl"))||((rs=We.canPlayType)===null||rs===void 0?void 0:rs.call(We,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((ss=We.canPlayType)===null||ss===void 0?void 0:ss.call(We,"video/mp4")),webm:Boolean((as=We.canPlayType)===null||as===void 0?void 0:as.call(We,"video/webm"))},Qe={h264:Boolean((ns=(Di=window.MediaSource)===null||Di===void 0?void 0:Di.isTypeSupported)===null||ns===void 0?void 0:ns.call(Di,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((os=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||os===void 0?void 0:os.call(Oi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((ls=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||ls===void 0?void 0:ls.call(Li,'video/webm; codecs="vp9"')),aac:Boolean((us=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||us===void 0?void 0:us.call(xi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ds=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||ds===void 0?void 0:ds.call(Bi,'audio/webm; codecs="opus"'))},Jt=(Qe.h264||Qe.h265)&&Qe.aac,hr=ze.hls&&Re.mp4,Vb=Boolean(window.WebSocket),Fb=()=>Object.keys(Qe).filter(i=>Qe[i]),Ub=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_SEP:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_WEBM:return ze.mse&&Re.webm&&Qe.vp9&&Qe.opus;case exports.VideoFormat.DASH_LIVE:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_ONDEMAND:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return hr||e&&ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.MPEG:return Re.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ze.webrtc&&Vb&&Qe.h264&&(Re.mp4||Re.webm);default:return a.assertNever(t)}}),jb=()=>Bl?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:hr?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Hb=()=>Bl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE]:hr?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE],Yn=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Gb=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const zn={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},qb={cacheDuration:12e4},Yb={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},zb={maxPausedTime:3e4},Wb={maxPausedTime:3e4};class Qb{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Ub([...Hb(),...jb()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new qn(s);const n=[...Yn(!0),...Yn(!1)];this.chromecastFormatsIterator=new qn(n.filter(o=>a.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),s=r.state!==D.None;this.params.desiredState.seekState.setState({state:D.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case he.SCREEN:return this.createScreenProvider(t);case he.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new nb(Object.assign(Object.assign({},o),{source:l,config:qb}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new VS(Object.assign(Object.assign({},o),{source:l,format:e,config:Wb})):new wb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),hr||!this.params.tuning.useHlsJs?new Cb(Object.assign(Object.assign({},o),{source:l})):new Rb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Nb(Object.assign(Object.assign({},o),{source:l,config:zb}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Db(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new tb(Object.assign(Object.assign({},o),{source:l,config:Yb}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bb({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new dS({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?he.CHROMECAST:he.SCREEN}chooseFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case he.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.next();case he.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case he.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case he.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return oi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Gb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:zn.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===he.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<zn.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Wn=(i,e,t)=>t*e+(1-t)*i;class Qn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${r}`),this.smoothedSeries$=new Ie(`smoothed_${r}`),this.reportedSeries$=new Ie(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let d=0;d<this.pastMeasures.length;d++)this.pastMeasures[d]!==void 0&&(t+=Math.pow(this.pastMeasures[d]-this.smoothed,2),r++);t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=Wn(this.slow,e,this.params.emaAlphaSlow),this.fast=Wn(this.fast,e,this.params.emaAlphaFast);const l=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=l(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}var ge;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(ge||(ge={}));const Ml=new Map;let lt=ge.RUNTIME;const cs=`vk-videoplayer-dummy-key-${Math.random()}`,Jb=()=>{try{localStorage.setItem(cs,"test"),localStorage.removeItem(cs),lt=ge.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(cs),lt=ge.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)lt=ge.RUNTIME;else throw e}else throw i}};Jb();const Kb=i=>{var e,t;switch(lt){case ge.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case ge.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case ge.RUNTIME:return Ml.get(i);default:a.assertNever(lt)}},Jn=(i,e)=>{switch(lt){case ge.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.RUNTIME:return void Ml.set(i,e);default:a.assertNever(lt)}},Xb=5e3,Kn="one_video_throughput",Xn="one_video_rtt",Fe=window.navigator.connection,Zn=()=>{const i=Fe==null?void 0:Fe.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},eo=()=>{const i=Fe==null?void 0:Fe.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},to=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ti{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ti.load(Kn)||(e.useBrowserEstimation?Zn():void 0)||Xb,n=(r=(t=ti.load(Xn))!==null&&t!==void 0?t:e.useBrowserEstimation?eo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(to(s,n,e.rttPenaltyRequestSize)),this.throughput=new Qn({initial:s,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new Qn({initial:n,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const o=()=>{const d=Zn();d&&this.throughput.next(d);const u=eo();a.isNonNullable(u)&&this.rtt.next(u)};Fe&&"onchange"in Fe&&this.subscription.add(a.fromEvent(Fe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{Jn(Kn,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{Jn(Xn,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>to(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>X(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ti.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=Kb(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const io={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}},Zb=i=>{const e={};for(const t of Object.keys(io)){const r=io[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var eg=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===D.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===D.None))),tg=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const ro=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var v,m;return p.state===D.Requested&&((m=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&m!==void 0?m:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:v})=>{var m,S;return p.state===D.Applying&&v.state===D.None&&((S=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&S!==void 0?S:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const v={from:o,to:p};o=void 0,n.next(v)}))});class ig{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:D.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:DS},this.initLogs(),this.tuning=Zb(e),this.chromecastInitializer=new fu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ti(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=tg(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Qb({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?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 e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:D.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(r=>r.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===D.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=a.now(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===D.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:D.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===D.Applying&&(this.desiredState.seekState.setState({state:D.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Wi(u)?1:Wi(c)?-1:Ui(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate);const u=e.providerOutput.element$.getValue();u&&this.info.intrinsicVideoSize$.next({width:u.videoWidth,height:u.videoHeight})})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(a.map(d=>d?{start:d.from,end:d.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(eg({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.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(a.map(d=>({id:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}})}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=di(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),CS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>NS(r)),this.providerContainer.current$.subscribe(({type:r})=>Ri("provider",r)),t.duration$.subscribe(r=>Ri("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Ri("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),t.position$.subscribe(new Ie("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),t.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Ri("codecs",Fb())}}const rg=`${cu}@${du}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=ig;exports.SDK_VERSION=rg;