@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/es2018.esm.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
- import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,ErrorCategory as r,isNullable as a,fromEvent as n,assertNever as o,merge as d,tap as h,map as u,observableFrom as l,filterChanged as c,assertNonNullable as p,debounce as m,timeout as f,combine as v,once as g,mapTo as S,filter as b,now as y,Observable as T,abortable as E,getExponentialDelay as w,interval as $,Logger as k}from'@vkontakte/videoplayer-shared/es2018.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2018.esm.js';import A from'lodash/debounce.js';var P,R,D,_,I,C;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS',t.HLS_LIVE='HLS_LIVE',t.WEB_RTC_LIVE='WEB_RTC_LIVE'}(R||(R={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(D||(D={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(I||(I={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(C||(C={}));class L{constructor(a){var n;this.connection$=new t(void 0),this.castState$=new t(_.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(_.NOT_AVAILABLE),this.subscription=new i,this.params=a,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const o='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${o}`}),a.isDisabled||!o)return;const d=s(null===(n=window.chrome)||void 0===n?void 0:n.cast),h=Boolean(window.__onGCastApiAvailable);var u;d?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},h||(u='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',u),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',category:r.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(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();a(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();a(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(n(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return o(t.sessionState)}}))).add(d(n(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(h((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),l([i.getCastState()])).pipe(c(),u(x),h((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{var n;const o=r===_.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();p(s);const r=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(a(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:r}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===_.CONNECTED?s(this.connection$.getValue())?_.CONNECTED:_.AVAILABLE:r)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',category:r.EXTERNAL_API,message:'[initializeCastApi] failed',thrown:t})}}}const x=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _.AVAILABLE;case cast.framework.CastState.CONNECTING:return _.CONNECTING;case cast.framework.CastState.CONNECTED:return _.CONNECTED;default:return o(t)}};var N='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},O=function(t){try{return!!t()}catch(t){return!0}},B=!O((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),M=B,U=Function.prototype,V=U.bind,F=U.call,q=M&&V.bind(F,F),H=M?function(t){return t&&q(t)}:function(t){return t&&function(){return F.apply(t,arguments)}},G=H,Y=G({}.toString),z=G(''.slice),Q=function(t){return z(Y(t),8,-1)},W=O,j=Q,J=Object,X=H(''.split),K=W((function(){return!J('z').propertyIsEnumerable(0)}))?function(t){return'String'==j(t)?X(t,''):J(t)}:J,Z=TypeError,tt=function(t){if(null==t)throw Z('Can\'t call method on '+t);return t},et=K,it=tt,st=function(t){return et(it(t))},rt={},at=function(t){return t&&t.Math==Math&&t},nt=at('object'==typeof globalThis&&globalThis)||at('object'==typeof window&&window)||at('object'==typeof self&&self)||at('object'==typeof N&&N)||function(){return this}()||Function('return this')(),ot=function(t){return'function'==typeof t},dt=nt,ht=Object.defineProperty,ut=function(t,e){try{ht(dt,t,{value:e,configurable:!0,writable:!0})}catch(i){dt[t]=e}return e},lt=nt['__core-js_shared__']||ut('__core-js_shared__',{}),ct=ot,pt=lt,mt=H(Function.toString);ct(pt.inspectSource)||(pt.inspectSource=function(t){return mt(t)});var ft,vt,gt=ot,St=pt.inspectSource,bt=nt.WeakMap,yt=gt(bt)&&/native code/.test(St(bt)),Tt=ot,Et=function(t){return'object'==typeof t?null!==t:Tt(t)},wt=!O((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),$t={},kt=Et,At=nt.document,Pt=kt(At)&&kt(At.createElement),Rt=function(t){return Pt?At.createElement(t):{}},Dt=Rt,_t=!wt&&!O((function(){return 7!=Object.defineProperty(Dt('div'),'a',{get:function(){return 7}}).a})),It=wt&&O((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),Ct=Et,Lt=String,xt=TypeError,Nt=function(t){if(Ct(t))return t;throw xt(Lt(t)+' is not an object')},Ot=B,Bt=Function.prototype.call,Mt=Ot?Bt.bind(Bt):function(){return Bt.apply(Bt,arguments)},Ut={},Vt=Ut,Ft=nt,qt=ot,Ht=function(t){return qt(t)?t:void 0},Gt=function(t,e){return arguments.length<2?Ht(Vt[t])||Ht(Ft[t]):Vt[t]&&Vt[t][e]||Ft[t]&&Ft[t][e]},Yt=H({}.isPrototypeOf),zt=nt,Qt=Gt('navigator','userAgent')||'',Wt=zt.process,jt=zt.Deno,Jt=Wt&&Wt.versions||jt&&jt.version,Xt=Jt&&Jt.v8;Xt&&(vt=(ft=Xt.split('.'))[0]>0&&ft[0]<4?1:+(ft[0]+ft[1])),!vt&&Qt&&(!(ft=Qt.match(/Edge\/(\d+)/))||ft[1]>=74)&&(ft=Qt.match(/Chrome\/(\d+)/))&&(vt=+ft[1]);var Kt=vt,Zt=O,te=!!Object.getOwnPropertySymbols&&!Zt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Kt&&Kt<41})),ee=te&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,ie=Gt,se=ot,re=Yt,ae=Object,ne=ee?function(t){return'symbol'==typeof t}:function(t){var e=ie('Symbol');return se(e)&&re(e.prototype,ae(t))},oe=String,de=function(t){try{return oe(t)}catch(t){return'Object'}},he=ot,ue=de,le=TypeError,ce=function(t){if(he(t))return t;throw le(ue(t)+' is not a function')},pe=ce,me=function(t,e){var i=t[e];return null==i?void 0:pe(i)},fe=Mt,ve=ot,ge=Et,Se=TypeError,be={exports:{}},ye=lt;(be.exports=function(t,e){return ye[t]||(ye[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 Te=tt,Ee=Object,we=function(t){return Ee(Te(t))},$e=we,ke=H({}.hasOwnProperty),Ae=Object.hasOwn||function(t,e){return ke($e(t),e)},Pe=H,Re=0,De=Math.random(),_e=Pe(1..toString),Ie=function(t){return'Symbol('+(void 0===t?'':t)+')_'+_e(++Re+De,36)},Ce=nt,Le=be.exports,xe=Ae,Ne=Ie,Oe=te,Be=ee,Me=Le('wks'),Ue=Ce.Symbol,Ve=Ue&&Ue.for,Fe=Be?Ue:Ue&&Ue.withoutSetter||Ne,qe=function(t){if(!xe(Me,t)||!Oe&&'string'!=typeof Me[t]){var e='Symbol.'+t;Oe&&xe(Ue,t)?Me[t]=Ue[t]:Me[t]=Be&&Ve?Ve(e):Fe(e)}return Me[t]},He=Mt,Ge=Et,Ye=ne,ze=me,Qe=function(t,e){var i,s;if('string'===e&&ve(i=t.toString)&&!ge(s=fe(i,t)))return s;if(ve(i=t.valueOf)&&!ge(s=fe(i,t)))return s;if('string'!==e&&ve(i=t.toString)&&!ge(s=fe(i,t)))return s;throw Se('Can\'t convert object to primitive value')},We=TypeError,je=qe('toPrimitive'),Je=function(t,e){if(!Ge(t)||Ye(t))return t;var i,s=ze(t,je);if(s){if(void 0===e&&(e='default'),i=He(s,t,e),!Ge(i)||Ye(i))return i;throw We('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),Qe(t,e)},Xe=ne,Ke=function(t){var e=Je(t,'string');return Xe(e)?e:e+''},Ze=wt,ti=_t,ei=It,ii=Nt,si=Ke,ri=TypeError,ai=Object.defineProperty,ni=Object.getOwnPropertyDescriptor;$t.f=Ze?ei?function(t,e,i){if(ii(t),e=si(e),ii(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=ni(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return ai(t,e,i)}:ai:function(t,e,i){if(ii(t),e=si(e),ii(i),ti)try{return ai(t,e,i)}catch(t){}if('get'in i||'set'in i)throw ri('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var oi,di,hi,ui=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},li=$t,ci=ui,pi=wt?function(t,e,i){return li.f(t,e,ci(1,i))}:function(t,e,i){return t[e]=i,t},mi=be.exports,fi=Ie,vi=mi('keys'),gi=function(t){return vi[t]||(vi[t]=fi(t))},Si={},bi=yt,yi=nt,Ti=H,Ei=Et,wi=pi,$i=Ae,ki=lt,Ai=gi,Pi=Si,Ri=yi.TypeError,Di=yi.WeakMap;if(bi||ki.state){var _i=ki.state||(ki.state=new Di),Ii=Ti(_i.get),Ci=Ti(_i.has),Li=Ti(_i.set);oi=function(t,e){if(Ci(_i,t))throw new Ri('Object already initialized');return e.facade=t,Li(_i,t,e),e},di=function(t){return Ii(_i,t)||{}},hi=function(t){return Ci(_i,t)}}else{var xi=Ai('state');Pi[xi]=!0,oi=function(t,e){if($i(t,xi))throw new Ri('Object already initialized');return e.facade=t,wi(t,xi,e),e},di=function(t){return $i(t,xi)?t[xi]:{}},hi=function(t){return $i(t,xi)}}var Ni={set:oi,get:di,has:hi,enforce:function(t){return hi(t)?di(t):oi(t,{})},getterFor:function(t){return function(e){var i;if(!Ei(e)||(i=di(e)).type!==t)throw Ri('Incompatible receiver, '+t+' required');return i}}},Oi=B,Bi=Function.prototype,Mi=Bi.apply,Ui=Bi.call,Vi='object'==typeof Reflect&&Reflect.apply||(Oi?Ui.bind(Mi):function(){return Ui.apply(Mi,arguments)}),Fi={},qi={},Hi={}.propertyIsEnumerable,Gi=Object.getOwnPropertyDescriptor,Yi=Gi&&!Hi.call({1:2},1);qi.f=Yi?function(t){var e=Gi(this,t);return!!e&&e.enumerable}:Hi;var zi=wt,Qi=Mt,Wi=qi,ji=ui,Ji=st,Xi=Ke,Ki=Ae,Zi=_t,ts=Object.getOwnPropertyDescriptor;Fi.f=zi?ts:function(t,e){if(t=Ji(t),e=Xi(e),Zi)try{return ts(t,e)}catch(t){}if(Ki(t,e))return ji(!Qi(Wi.f,t,e),t[e])};var es=O,is=ot,ss=/#|\.prototype\./,rs=function(t,e){var i=ns[as(t)];return i==ds||i!=os&&(is(e)?es(e):!!e)},as=rs.normalize=function(t){return String(t).replace(ss,'.').toLowerCase()},ns=rs.data={},os=rs.NATIVE='N',ds=rs.POLYFILL='P',hs=rs,us=ce,ls=B,cs=H(H.bind),ps=function(t,e){return us(t),void 0===e?t:ls?cs(t,e):function(){return t.apply(e,arguments)}},ms=nt,fs=Vi,vs=H,gs=ot,Ss=Fi.f,bs=hs,ys=Ut,Ts=ps,Es=pi,ws=Ae,$s=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 fs(t,this,arguments)};return e.prototype=t.prototype,e},ks=function(t,e){var i,s,r,a,n,o,d,h,u=t.target,l=t.global,c=t.stat,p=t.proto,m=l?ms:c?ms[u]:(ms[u]||{}).prototype,f=l?ys:ys[u]||Es(ys,u,{})[u],v=f.prototype;for(r in e)i=!bs(l?r:u+(c?'.':'#')+r,t.forced)&&m&&ws(m,r),n=f[r],i&&(o=t.dontCallGetSet?(h=Ss(m,r))&&h.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?Ts(a,ms):t.wrap&&i?$s(a):p&&gs(a)?vs(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Es(d,'sham',!0),Es(f,r,d),p&&(ws(ys,s=u+'Prototype')||Es(ys,s,{}),Es(ys[s],r,a),t.real&&v&&!v[r]&&Es(v,r,a)))},As=wt,Ps=Ae,Rs=Function.prototype,Ds=As&&Object.getOwnPropertyDescriptor,_s=Ps(Rs,'name'),Is={EXISTS:_s,PROPER:_s&&'something'===function(){}.name,CONFIGURABLE:_s&&(!As||As&&Ds(Rs,'name').configurable)},Cs={},Ls=Math.ceil,xs=Math.floor,Ns=Math.trunc||function(t){var e=+t;return(e>0?xs:Ls)(e)},Os=function(t){var e=+t;return e!=e||0===e?0:Ns(e)},Bs=Os,Ms=Math.max,Us=Math.min,Vs=Os,Fs=Math.min,qs=function(t){return t>0?Fs(Vs(t),9007199254740991):0},Hs=function(t){return qs(t.length)},Gs=st,Ys=function(t,e){var i=Bs(t);return i<0?Ms(i+e,0):Us(i,e)},zs=Hs,Qs=function(t){return function(e,i,s){var r,a=Gs(e),n=zs(a),o=Ys(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}},Ws={includes:Qs(!0),indexOf:Qs(!1)},js=Ae,Js=st,Xs=Ws.indexOf,Ks=Si,Zs=H([].push),tr=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],er=function(t,e){var i,s=Js(t),r=0,a=[];for(i in s)!js(Ks,i)&&js(s,i)&&Zs(a,i);for(;e.length>r;)js(s,i=e[r++])&&(~Xs(a,i)||Zs(a,i));return a},ir=tr,sr=Object.keys||function(t){return er(t,ir)},rr=wt,ar=It,nr=$t,or=Nt,dr=st,hr=sr;Cs.f=rr&&!ar?Object.defineProperties:function(t,e){or(t);for(var i,s=dr(e),r=hr(e),a=r.length,n=0;a>n;)nr.f(t,i=r[n++],s[i]);return t};var ur,lr=Gt('document','documentElement'),cr=Nt,pr=Cs,mr=tr,fr=Si,vr=lr,gr=Rt,Sr=gi('IE_PROTO'),br=function(){},yr=function(t){return'<script>'+t+'<\/script>'},Tr=function(t){t.write(yr('')),t.close();var e=t.parentWindow.Object;return t=null,e},Er=function(){try{ur=new ActiveXObject('htmlfile')}catch(t){}var t,e;Er='undefined'!=typeof document?document.domain&&ur?Tr(ur):((e=gr('iframe')).style.display='none',vr.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(yr('document.F=Object')),t.close(),t.F):Tr(ur);for(var i=mr.length;i--;)delete Er.prototype[mr[i]];return Er()};fr[Sr]=!0;var wr,$r,kr,Ar=Object.create||function(t,e){var i;return null!==t?(br.prototype=cr(t),i=new br,br.prototype=null,i[Sr]=t):i=Er(),void 0===e?i:pr.f(i,e)},Pr=!O((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Rr=Ae,Dr=ot,_r=we,Ir=Pr,Cr=gi('IE_PROTO'),Lr=Object,xr=Lr.prototype,Nr=Ir?Lr.getPrototypeOf:function(t){var e=_r(t);if(Rr(e,Cr))return e[Cr];var i=e.constructor;return Dr(i)&&e instanceof i?i.prototype:e instanceof Lr?xr:null},Or=pi,Br=function(t,e,i,s){return s&&s.enumerable?t[e]=i:Or(t,e,i),t},Mr=O,Ur=ot,Vr=Ar,Fr=Nr,qr=Br,Hr=qe('iterator'),Gr=!1;[].keys&&('next'in(kr=[].keys())?($r=Fr(Fr(kr)))!==Object.prototype&&(wr=$r):Gr=!0);var Yr=null==wr||Mr((function(){var t={};return wr[Hr].call(t)!==t}));Ur((wr=Yr?{}:Vr(wr))[Hr])||qr(wr,Hr,(function(){return this}));var zr={IteratorPrototype:wr,BUGGY_SAFARI_ITERATORS:Gr},Qr={};Qr[qe('toStringTag')]='z';var Wr='[object z]'===String(Qr),jr=Wr,Jr=ot,Xr=Q,Kr=qe('toStringTag'),Zr=Object,ta='Arguments'==Xr(function(){return arguments}()),ea=jr?Xr: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=Zr(t),Kr))?i:ta?Xr(e):'Object'==(s=Xr(e))&&Jr(e.callee)?'Arguments':s},ia=ea,sa=Wr?{}.toString:function(){return'[object '+ia(this)+']'},ra=Wr,aa=$t.f,na=pi,oa=Ae,da=sa,ha=qe('toStringTag'),ua=function(t,e,i,s){if(t){var r=i?t:t.prototype;oa(r,ha)||aa(r,ha,{configurable:!0,value:e}),s&&!ra&&na(r,'toString',da)}},la=zr.IteratorPrototype,ca=Ar,pa=ui,ma=ua,fa=rt,va=function(){return this},ga=(TypeError,H);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=ga(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Sa=ks,ba=Mt,ya=function(t,e,i,s){var r=e+' Iterator';return t.prototype=ca(la,{next:pa(+!s,i)}),ma(t,r,!1,!0),fa[r]=va,t},Ta=Nr,Ea=ua,wa=Br,$a=rt,ka=Is.PROPER,Aa=zr.BUGGY_SAFARI_ITERATORS,Pa=qe('iterator'),Ra=function(){return this},Da=st,_a=rt,Ia=Ni;$t.f;var Ca=function(t,e,i,s,r,a,n){ya(i,e,s);var o,d,h,u=function(t){if(t===r&&f)return f;if(!Aa&&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)}},l=e+' Iterator',c=!1,p=t.prototype,m=p[Pa]||p['@@iterator']||r&&p[r],f=!Aa&&m||u(r),v='Array'==e&&p.entries||m;if(v&&(o=Ta(v.call(new t)))!==Object.prototype&&o.next&&(Ea(o,l,!0,!0),$a[l]=Ra),ka&&'values'==r&&m&&'values'!==m.name&&(c=!0,f=function(){return ba(m,this)}),r)if(d={values:u('values'),keys:a?f:u('keys'),entries:u('entries')},n)for(h in d)(Aa||c||!(h in p))&&wa(p,h,d[h]);else Sa({target:e,proto:!0,forced:Aa||c},d);return n&&p[Pa]!==f&&wa(p,Pa,f,{name:r}),$a[e]=f,d},La=Ia.set,xa=Ia.getterFor('Array Iterator');Ca(Array,'Array',(function(t,e){La(this,{type:'Array Iterator',target:Da(t),index:0,kind:e})}),(function(){var t=xa(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'),_a.Arguments=_a.Array;var Na=rt,Oa=qe('iterator'),Ba=Array.prototype,Ma=ea,Ua=me,Va=rt,Fa=qe('iterator'),qa=function(t){if(null!=t)return Ua(t,Fa)||Ua(t,'@@iterator')||Va[Ma(t)]},Ha=Mt,Ga=ce,Ya=Nt,za=de,Qa=qa,Wa=TypeError,ja=Mt,Ja=Nt,Xa=me,Ka=ps,Za=Mt,tn=Nt,en=de,sn=function(t){return void 0!==t&&(Na.Array===t||Ba[Oa]===t)},rn=Hs,an=Yt,nn=function(t,e){var i=arguments.length<2?Qa(t):e;if(Ga(i))return Ya(Ha(i,t));throw Wa(za(t)+' is not iterable')},on=qa,dn=function(t,e,i){var s,r;Ja(t);try{if(!(s=Xa(t,'return'))){if('throw'===e)throw i;return i}s=ja(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return Ja(s),i},hn=TypeError,un=function(t,e){this.stopped=t,this.result=e},ln=un.prototype,cn=Ke,pn=$t,mn=ui,fn=function(t,e,i){var s,r,a,n,o,d,h,u=i&&i.that,l=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=Ka(e,u),v=function(t){return s&&dn(s,'normal',t),new un(!0,t)},g=function(t){return l?(tn(t),m?f(t[0],t[1],v):f(t[0],t[1])):m?f(t,v):f(t)};if(c)s=t.iterator;else if(p)s=t;else{if(!(r=on(t)))throw hn(en(t)+' is not iterable');if(sn(r)){for(a=0,n=rn(t);n>a;a++)if((o=g(t[a]))&&an(ln,o))return o;return new un(!1)}s=nn(t,r)}for(d=c?t.next:s.next;!(h=Za(d,s)).done;){try{o=g(h.value)}catch(t){dn(s,'throw',t)}if('object'==typeof o&&o&&an(ln,o))return o}return new un(!1)},vn=function(t,e,i){var s=cn(e);s in t?pn.f(t,s,mn(0,i)):t[s]=i};ks({target:'Object',stat:!0},{fromEntries:function(t){var e={};return fn(t,(function(t,i){vn(e,t,i)}),{AS_ENTRIES:!0}),e}});var gn=Ut.Object.fromEntries,Sn={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},bn=nt,yn=ea,Tn=pi,En=rt,wn=qe('toStringTag');for(var $n in Sn){var kn=bn[$n],An=kn&&kn.prototype;An&&yn(An)!==wn&&Tn(An,wn,$n),En[$n]=En.Array}var Pn,Rn=gn;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Pn||(Pn={}));var Dn,_n=(t,e=0,i=Pn.OFFSET_P)=>{switch(i){case Pn.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case Pn.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:o(i)}return t},In=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(Dn||(Dn={}));const Cn={[Dn.Q_144P]:{width:256,height:144},[Dn.Q_240P]:{width:428,height:240},[Dn.Q_360P]:{width:640,height:360},[Dn.Q_480P]:{width:856,height:480},[Dn.Q_720P]:{width:1280,height:720},[Dn.Q_1080P]:{width:1920,height:1080},[Dn.Q_1440P]:{width:2560,height:1440},[Dn.Q_2160P]:{width:3840,height:2160},[Dn.Q_4320P]:{width:7680,height:4320}},Ln=(t,e)=>Cn[t].height>Cn[e].height,xn=(t,e)=>Cn[t].height<Cn[e].height,Nn=Object.keys(Cn).sort(((t,e)=>xn(t,e)?-1:1)),On=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return Nn.find((t=>{const e=Cn[t];return e.width>=s&&e.height>=i}))},Bn=t=>t===Dn.INVARIANT;class Mn{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=d(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=d(this.transitionEnded$,this.forceChanged$),this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var Un;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Un||(Un={}));class Vn{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new Mn(Un.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)if((null==s?void 0:s.to)===P.PAUSED||r.state!==C.Requested||t===Un.STOPPED)switch(i){case P.PLAYING:switch(t){case Un.PLAYING:break;case Un.PAUSED:case Un.READY:this.videoState.startTransitionTo(Un.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Un.STOPPED:this.videoState.startTransitionTo(Un.READY),this.prepare();break;default:o(t)}break;case P.PAUSED:switch(t){case Un.PLAYING:this.videoState.startTransitionTo(Un.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Un.PAUSED:break;case Un.READY:this.videoState.startTransitionTo(Un.PAUSED),this.videoState.setState(Un.PAUSED);break;case Un.STOPPED:this.videoState.startTransitionTo(Un.READY),this.prepare();break;default:o(t)}break;default:o(i)}else this.seek(r.position)}else t!==Un.STOPPED&&(this.videoState.startTransitionTo(Un.STOPPED),this.stop())},this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case R.MPEG:case R.DASH:case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:case R.HLS:case R.HLS_ONDEMAND:return!1;case R.HLS_LIVE:case R.DASH_LIVE:case R.DASH_LIVE_WEBM:case R.WEB_RTC_LIVE:return!0;default:return o(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(d(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const s=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(m(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),t.add(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),In(this.params.desiredState.playbackState,P.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:o(i)}})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(d(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(Un.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(Un.PLAYING),In(this.params.desiredState.playbackState,P.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Un.PAUSED&&t!==Un.PLAYING||(this.videoState.setState(Un.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Un.PLAYING&&t!==Un.PAUSED||(this.videoState.setState(Un.PLAYING),In(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Un.READY&&this.videoState.setState(Un.READY)}handleRemoteStop(){this.videoState.getState()!==Un.STOPPED&&this.videoState.setState(Un.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){var e;const i=this.params.source;let a,n,d;switch(t){case R.MPEG:{const e=i[t];p(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===Dn.INVARIANT?1:e===Dn.INVARIANT?-1:xn(t,e)?1:-1))[0];p(s);const r=e[s];p(r),a=r,n='video/mp4',d=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS:case R.HLS_ONDEMAND:{const e=i[t];p(e),a=e.url,n='application/x-mpegurl',d=chrome.cast.media.StreamType.BUFFERED;break}case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:{const e=i[t];p(e),a=e.url,n='application/dash+xml',d=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS_LIVE:{const e=i[t];p(e),a=_n(e.url),n='application/x-mpegurl',d=chrome.cast.media.StreamType.LIVE;break}case R.DASH:case R.DASH_LIVE:case R.WEB_RTC_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',category:r.VIDEO_PIPELINE,message:t,thrown:e}),e}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return o(t)}const h=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:a,n);h.contentUrl=a,h.streamType=d,h.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:l}=this.params.meta;return s(u)&&(h.metadata.title=u),s(l)&&(h.metadata.subtitle=l),h}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===C.Applying||i.state===C.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(f(7e3).subscribe((()=>e('timeout(7000)'))))}));Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',category:r.VIDEO_PIPELINE,message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}class Fn{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 qn extends Fn{constructor(){super(),this.listeners||Fn.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 Hn{constructor(){Object.defineProperty(this,'signal',{value:new qn,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 Gn(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&&(Hn.prototype[Symbol.toStringTag]='AbortController',qn.prototype[Symbol.toStringTag]='AbortSignal');const Yn=Gn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zn=Yn?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(!Gn({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,Qn=Yn?zn.fetch:window.fetch;Yn?zn.Request:window.Request;const Wn=Yn?Hn:window.AbortController,jn=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Jn{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[r,a]=jn(s.request);if(r>=i.from&&a<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),r=this.activeRequests.get(i.url);s&&r&&r.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(jn),s=i[0][0];let a=i[0][1];for(let t=1;t<i.length&&a<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(a=Math.max(a,e))}a=0===s?Math.max(a,s+this.params.minInitSize):Math.max(a,s+this.params.minDataSize);const n=new URL(t,location.href);n.searchParams.append('bytes',`${s}-${a}`);const o=n.toString(),d=new Wn,h=d.signal,u={url:t,from:s,to:a,loaded:0,data:null,abortController:d};h.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const l=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',category:r.PARSER,message:'Error parsing response data',thrown:t}),t};return Qn(o,{signal:h}).then((t=>{var e,i,r;if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const d=n.getReader(),h=parseInt(null!==(r=t.headers.get('Content-Length'))&&void 0!==r?r:'',10)||a-s+1;u.data=new ArrayBuffer(h);const c=new Uint8Array(u.data),p=async({done:t,value:e})=>{t?this.onBigRequestProgress(u):e&&(c.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),await(null==d?void 0:d.read().then(p,Jn.suppressStreamErrors).catch(l)))};null==d||d.read().then(p,Jn.suppressStreamErrors).catch(l)}),Jn.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,d,h,u,l,c,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]=jn(m),g=f>=e&&v<=e+s,S=e>=f&&e+s<v,b=r.slice(f-e,Math.min(v-e+1,s));if((g||S)&&(m.requestStartDate=null!==(o=m.requestStartDate)&&void 0!==o?o:new Date,m.firstByteDate=null!==(d=m.firstByteDate)&&void 0!==d?d:new Date,m.bytesLoaded=b.byteLength,m.bytesTotal=i-e),g){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(h=this.dashJsRequestQueue.get(t))&&void 0!==h?h:[]).filter((t=>t!==n))),null===(u=n.success)||void 0===u||u.call(n,b,'',t);const e=a?Array.from(a.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(m,t,null!==(c=null==a?void 0:a.status)&&void 0!==c?c:200,e,[])}else S&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var a,n,o,d;if(null===(n=(a=this.params).onError)||void 0===n||n.call(a,{id:'BigRequest',category:r.NETWORK,message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const h=null!==(o=this.dashJsRequestQueue.get(t))&&void 0!==o?o:[];for(const t of h){const[r,a]=jn(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(d=null==t?void 0:t.error)||void 0===d||d.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=jn(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 Xn{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(Xn.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;Xn.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const Kn=(t,e)=>{const i=new Jn(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 Xn(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var Zn=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)},to=i=>{const r=new t(1/0),a=new e,n=new t(void 0),o=new t(void 0);let d=NaN,h=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{var e,i,a,d,h;const u=Rn(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in u||'x-playback-duration-millis'in u){const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)}const l=null!==(d=u['x-delivery-type'])&&void 0!==d?d:I.HTTP1,c=null!==(h={1:!0,0:!1}[u['x-reused']])&&void 0!==h?h:void 0;n.next(l),o.next(c)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!h&&(h=!0,a.next(Date.now()-d)),i(...t)},d=Date.now(),h=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a,connectionReused$:o,connectionType$:n}},eo=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},io=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 so=(t,e,s,{equal:r=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=a(n),l=new i;return n&&l.add(n.subscribe((e=>{const i=t.getState();r(e,i)&&t.setState(e)}),o)),r(h,d)||(s(d),u&&t.setState(d)),l.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),u&&t.setState(e.to)}),o)),l},ro=(t,e,i)=>so(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),ao=(t,e,i,r)=>so(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),no=(t,e,i,r)=>so(e,(()=>t.playbackRate),(e=>{s(e)&&(t.playbackRate=e)}),{changed$:i,onError:r}),oo=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class ho{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const a=t=>{this.error$.next({id:'TextTracksManager',category:r.WTF,message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(so(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:a})),this.subscription.add(so(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:a})),this.subscription.add(so(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){p(this.video);const{textTracks:t}=this.video;this.subscription.add(n(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(d(n(t,'addtrack'),n(t,'removetrack'),l(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(d(n(t,'change'),l(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(n(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(n(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){p(this.video);const e=[...this.video.textTracks];return t?e:e.filter(ho.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){p(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&oo(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){p(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){p(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var uo=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 lo{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 co=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class po{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 mo=(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 fo=t=>{const i=e=>n(t,e).pipe(S(void 0)),a=d(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>n(t,e)))).pipe(u((e=>'ended'===e.type?t.readyState<2:t.readyState<3)),c()),o=d(n(t,'progress'),n(t,'timeupdate')).pipe(u((()=>mo(t.buffered,t.currentTime)))),h=co()?v({play:i('play').pipe(g()),playing:i('playing')}).pipe(S(void 0)):i('playing'),l=n(t,'volumechange').pipe(u((()=>({muted:t.muted,volume:t.volume})))),p=n(t,'ratechange').pipe(u((()=>t.playbackRate))),m=n(t,'error').pipe(b((()=>Boolean(t.error||t.played.length))),u((()=>{var e;const i=t.error;return{id:i?`MediaError#${i.code}`:'HtmlVideoError',category:r.VIDEO_PIPELINE,message:i?i.message:'Error event from HTML video element',thrown:null!==(e=t.error)&&void 0!==e?e:void 0}}))),f=n(t,'timeupdate').pipe(u((()=>t.currentTime))),y=new e;let T;return f.subscribe((e=>{t.loop&&s(T)&&s(e)&&T>=t.duration-.3&&e<=.3&&y.next(T),T=e})),{playing$:h,pause$:i('pause').pipe(b((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:y,error$:m,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:f,durationChange$:n(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:a,currentBuffer$:o,volumeState$:l,playbackRateState$:p}},vo=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var go=we,So=Hs,bo=Os;ks({target:'Array',proto:!0},{at:function(t){var e=go(this),i=So(e),s=bo(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var yo=Gt('Array','at');let To=!1,Eo={};const wo=t=>{t(Eo)},$o=(t,e)=>{var i;To&&(Eo.meta=null!==(i=Eo.meta)&&void 0!==i?i:{},Eo.meta[t]=e)};class ko{constructor(t){this.name=t}next(t){var e,i;if(!To)return;Eo.series=null!==(e=Eo.series)&&void 0!==e?e:{};const s=null!==(i=Eo.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Eo.series[this.name]=s}}const Ao=new ko('best_bitrate');class Po{constructor(){this.history={}}recordSelection(t){this.history[t.id]=y()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Ro=(t,{container:e,throughput:i,tuning:r,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:h,current:u,history:l})=>{var c,p,m,f;const v=r.usePixelRatio&&null!==(c=window.devicePixelRatio)&&void 0!==c?c:1,g=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*r.containerSizeFactor,height:e.height*v*r.containerSizeFactor},S=g&&On(g),b=r.considerPlaybackRate&&s(h)?h:1,T=t.filter((t=>!Bn(t.quality))).sort(((t,e)=>Ln(t.quality,e.quality)?-1:1)),E=null===(p=yo(T,-1))||void 0===p?void 0:p.quality,w=null===(m=yo(T,0))||void 0===m?void 0:m.quality,$=a(n)||s(n.min)&&s(n.max)&&xn(n.max,n.min)||s(n.min)&&w&&Ln(n.min,w)||s(n.max)&&E&&xn(n.max,E),k=b*(A=null!=d?d:.5,P=r.bitrateFactorAtEmptyBuffer,R=r.bitrateFactorAtFullBuffer,(P-R)*Math.pow(2,-10*A)+R);var A,P,R;const D=T.filter((t=>{const e=!S||xn(t.quality,S),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*k,l=r.lazyQualitySwitch&&s(r.minBufferToSwitchUp)&&u&&!Bn(u.quality)&&(null!=d?d:0)<r.minBufferToSwitchUp&&Ln(t.quality,u.quality),c=$||(a(n.max)||(p=t.quality,m=n.max,Cn[p].height<=Cn[m].height))&&(a(n.min)||((t,e)=>Cn[t].height>=Cn[e].height)(t.quality,n.min));var p,m;return e&&h&&!l&&c}))[0];D&&D.bitrate&&Ao.next(D.bitrate);const _=null!==(f=null!=D?D:T[Math.ceil((T.length-1)/2)])&&void 0!==f?f:t[0],I=_&&l&&l.history[_.id]&&y()-l.history[_.id]<=r.trackCooldown&&(!l.last||_.id!==l.last.id);if((null==_?void 0:_.id)&&l&&!I&&l.recordSelection(_),I&&(null==l?void 0:l.last)){const t=l.last;return null==l||l.recordSwitch(t),t}return null==l||l.recordSwitch(_),_};var Do=t=>new URL(t).hostname;const _o=(t,e=300)=>new T((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()})),Io={};var Co;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Co||(Co={}));const Lo=(t,e)=>new T((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class xo{constructor(e){this.subscription=new i,this.videoState=new Mn(Co.DOWNLOADING_LIB),this.textTracksManager=new ho,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new lo,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==Co.DOWNLOADING_LIB&&t!==Co.STREAM_INITIALIZED)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&t!==Co.STOPPED&&e!==P.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case Co.STOPPED:break;case Co.PLAYING:case Co.PAUSED:case Co.READY:this.stop();break;default:o(t)}break;case P.PLAYING:switch(t){case Co.PLAYING:break;case Co.PAUSED:r&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Co.READY:this.play();break;case Co.STOPPED:this.prepare();break;default:o(t)}break;case P.PAUSED:switch(t){case Co.PLAYING:this.pause(),this.liveOffset.pause();break;case Co.PAUSED:break;case Co.READY:this.videoState.setState(Co.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED);break;case Co.STOPPED:this.prepare();break;default:o(t)}break;default:o(e)}},this.video=uo(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',category:r.NETWORK,message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Io.MediaPlayer=e.MediaPlayer,Io.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){p(Io.MediaPlayer,'dashjs not loaded'),p(Io.Debug,'dashjs not loaded'),this.player=Io.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?vo(t.frameRate+''):void 0),!0)));(this.params.format===R.DASH_WEBM||this.params.format===R.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Kn(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&&io(this.player),Zn(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:eo})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Co.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',category:r.WTF,message:'DashIFProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(_o(this.video),this.elementSize$),n(Lo(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),n(Lo(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const o=Lo(this.player,'qualityChangeRendered').pipe(b((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));o.pipe(b(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(b((({to:t})=>t===Co.STREAM_INITIALIZED)),g()).subscribe((()=>{this.subscription.add(so(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(a(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:o.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add(so(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),n(Lo(this.player,'bufferStateChanged').pipe(b((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),n(Lo(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type'))&&void 0!==s?s:I.HTTP1,d=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(d),t.hostname$.next(Do(i))})),n(Lo(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=On(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(Co.STREAM_INITIALIZED),this.videoState.startTransitionTo(Co.READY)})),n(Lo(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)})),n(d(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=Ro(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),n(v({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(b(s))}).pipe(b((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const h=Lo(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));n(v({availableFrom:this.availableFrom$.pipe(b(s)),currentTime:h}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),n(h.pipe(b((()=>!1===this.isLive$.getValue()))),t.position$),n(Lo(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),n(Lo(this.player,'playbackEnded'),t.endedEvent$),n(Lo(this.player,'playbackProgress').pipe(u((()=>mo(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),n(Lo(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Co.PLAYING),In(e.playbackState,P.PLAYING)})),n(Lo(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Co.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),n(Lo(this.player,'playbackPaused'),(()=>{this.videoState.setState(Co.PAUSED),In(e.playbackState,P.PAUSED)})),n(Lo(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Co.READY&&this.videoState.setState(Co.READY)})),n(this.isLive$,t.isLive$),n(_o(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));n(d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0)),this.syncPlayback);const{playbackDuration$:c,ping$:p,connectionType$:f,connectionReused$:y}=to(this.player);n(f,this.params.output.httpConnectionType$),n(y,this.params.output.httpConnectionReused$),n(c,this.maxSeekBackTime$),n(p.pipe(g()),t.firstBytesEvent$),n(Lo(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&n(v({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),n(h.pipe(b((t=>t>this.params.tuning.insufficientBufferRuleMargin)),g()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Lo(this.player,'manifestLoaded').pipe(g()).subscribe((()=>{this.subscription.add(Lo(this.player,'playbackPlaying').pipe(g(),S(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(ro(this.video,e.isLooped,i));const{volumeState$:T,looped$:E,playbackRateState$:w}=fo(this.video);this.subscription.add(ao(this.video,e.volume,T,i)),this.subscription.add(T.subscribe(t.volume$,i)),this.subscription.add(E.subscribe(t.loopedEvent$)),this.subscription.add(no(this.video,e.playbackRate,w,i))}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(Co.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Co.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=_n(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Pn.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Co.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Co.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 No=t=>{switch(t){case'mobile':return Dn.Q_144P;case'lowest':return Dn.Q_240P;case'low':return Dn.Q_360P;case'sd':case'medium':return Dn.Q_480P;case'hd':case'high':return Dn.Q_720P;case'fullhd':case'full':return Dn.Q_1080P;case'quadhd':case'quad':return Dn.Q_1440P;case'ultrahd':case'ultra':return Dn.Q_2160P}},Oo=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function Bo(){return y()}function Mo(t){return Bo()-t}function Uo(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 Vo(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,h,u,l=!1,c=0,m=!1,f='arraybuffer',v=7e3,g=2e3,S=()=>{if(l)return;p(h);const t=Mo(h);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!l){if(--c>=0)return S(),void(r&&r());l=!0,u&&u(),i&&i()}},y=()=>{h=Bo(),o=new a,o.open('get',t);let i,s=0,r=0;const c=()=>(p(h),Math.max(h,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=Bo();n.updateChunk&&t.loaded>s&&(n.updateChunk(c(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(l)return;p(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(c(),t)}u&&u(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),m){const t=()=>{p(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=Bo(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=f,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(m=t,T),withJSONResponse:()=>(f='json',T),withRetryCount:t=>(c=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(u=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),l=!0,u&&u()}};return T}class Fo{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 qo{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=Bo(),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=Vo(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Bo()-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=Bo()}_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=Bo();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 Ho{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 Fo(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Uo(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=Uo(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 t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const a=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:'playing'})):a()}))};a()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new qo(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:r}=this.params;let n=!1,o=null,d=null,h=null,u=null,l=!1;const c=()=>{const t=n&&(!l||l===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{h&&h.abort(),h=Vo(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,i)=>{p(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=Bo()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=t=>{let i;const a=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),l=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=i.dur.length-1;for(;a>=0&&(r-=i.dur[a],!(r<=0));--a);t=Math.min(a,i.dur.length-1-s),t=Math.max(t,0)}return h(t,!0)},m=(t,e,i)=>{u&&u.abort(),u=Vo(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!c())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let u=0;for(let t=0;t<i.dur.length;++t)u+=i.dur[t];u>0&&(p(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),r({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=a();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return h(i);return l()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=a(),r=t?t.chunkIdx+1:0,n=r-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),l();if(!(n>=s))return h(r-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),p(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:e=>{const{videoElement:i,logger:s}=this.params;let r,d,h,l,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Bo(),s=Math.min(1e4,e-i);w=i;const r=()=>{u||c()&&E.seek((()=>{c()&&(w=Bo(),k(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},k=()=>{let e;for(;e=E.nextChunk(l);)l=e,_(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));D(i)}else $()},A=(t,e)=>{if(!c()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{c()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Bo(),h=i.currentTime;!this.paused&&i.buffered.length>1&&g===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==h&&(g=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(r=this.sourceBuffer.buffered.start(0),a=h,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},P=()=>{d&&r&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,k()})))},R=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{c()&&f(R(t),((e,i)=>{if(c()){if(i/=1e3,d=e,h=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},_=t=>{c()&&(p(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(R(t),!1)))},I=e=>{c()&&(t.cachedHeader=e,A(e,(()=>{r=!0,P()})))};n=!0,E.seek((t=>{c()&&(w=Bo(),t?(l=t,!a(e)||t.startTS>e?D(t):(h=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},l}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,p(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Bo();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&&Mo(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=Bo();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Vo(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;Oo(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 Go;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Go||(Go={}));const Yo=[Go.PAUSED,Go.PLAYING,Go.READY],zo=[Go.PAUSED,Go.PLAYING,Go.READY];class Qo{constructor(e){this.subscription=new i,this.videoState=new Mn(Go.STOPPED),this.representations$=new t([]),this.textTracksManager=new ho,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new lo,this._dashCb=t=>{var e,i,a,n;switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,category:r.WTF,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,r=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),a=null!==(i=No(t.name))&&void 0!==i?i:On(t.video),n=t.bitrate/1e3,o={...t.video};if(!a)continue;const d={id:s,quality:a,bitrate:n,size:o};r.push({track:d,representation:t})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),(null===(a=this.videoState.getTransition())||void 0===a?void 0:a.to)===Go.MANIFEST_READY&&this.videoState.setState(Go.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(n=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===n?void 0:n.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r!==P.STOPPED){if(!i){if(zo.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}if((null==a?void 0:a.to)!==P.PAUSED&&n.state===C.Requested&&Yo.includes(e))this.seek(n.position-this.liveOffset.getTotalPausedTime());else switch(e){case Go.STOPPED:return this.videoState.startTransitionTo(Go.MANIFEST_READY),void this.dash.attachSource(_n(this.params.source.url));case Go.MANIFEST_READY:this.videoState.startTransitionTo(Go.READY),this.prepare();break;case Go.READY:return void(r===P.PAUSED?this.videoState.setState(Go.PAUSED):r===P.PLAYING&&(this.videoState.startTransitionTo(Go.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Go.PAUSED)}))));case Go.PLAYING:return void(r===P.PAUSED&&(this.videoState.startTransitionTo(Go.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Go.PAUSED:return void(r===P.PLAYING&&(this.videoState.startTransitionTo(Go.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(Go.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return o(e)}}}else e!==Go.STOPPED&&(this.videoState.startTransitionTo(Go.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Go.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const a=t=>{e.output.error$.next({id:'DashLiveProvider',category:r.WTF,message:'DashLiveProvider internal logic error',thrown:t})};d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=uo(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(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const n=fo(this.video);this.subscription.add(n.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Go.READY&&this.videoState.setState(Go.READY)}),a)).add(n.pause$.subscribe((()=>{this.videoState.setState(Go.PAUSED)}),a)).add(n.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Go.PLAYING)}),a)).add(n.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(v({zeroTime:this.zeroTime$.pipe(b(s)),position:n.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),a)).add(ro(this.video,this.params.desiredState.isLooped,a)).add(ao(this.video,this.params.desiredState.volume,n.volumeState$,a)).add(n.volumeState$.subscribe(this.params.output.volume$,a)).add(no(this.video,this.params.desiredState.playbackRate,n.playbackRateState$,a)).add(n.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(n.playing$.subscribe(this.params.output.firstFrameEvent$)).add(n.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&Cn[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Go.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case Go.MANIFEST_READY:case Go.READY:break;case Go.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case Go.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return o(t.to)}}),a)).add(d(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0)).subscribe(this.syncPlayback,a))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Ho({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),h=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),u=!h&&s(d)?d:null===(a=Ro(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,l=null===(n=o.find((({track:t})=>t.id===u)))||void 0===n?void 0:n.representation;p(l,'Representations missing'),this.dash.startPlay(l,h),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(u),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(h)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;p(i,`No such representation ${t}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(_n(this.params.source.url,i))}}var Wo=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?I.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}},jo=(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 Jo{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{var e,i,s,r,a,n,o,d;if(p(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Rn(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Xo{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,l=0;const c=t=>{s(Xo._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=eo(p)),this._lastXhr=new Jo(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&c(t),0===u)return void(u=Date.now());l=t.length-h;const e=Date.now()-u;l>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:l,duration:e,speed:8*l/(e/1e3)}),l=0,h=t.length,u=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=Xo._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 Ko{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=eo(i)),new Jo(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,h,u,l,c,p,m,f,v,g,S,b,y,T,E,w,$;const k=t.getElementsByTagName('SegmentBase')[0],A=k&&r(k,'indexRange').split('-'),P=k&&k.getElementsByTagName('Initialization')[0],R=P&&r(P,'range').split('-');if(!R||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(u=null===(h=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===h?void 0:h[0])||void 0===u?void 0:u.data),c=null!==(l=e.getAttribute('lang'))&&void 0!==l?l:void 0;a&&n.push({id:r,url:a,language:c})}return}const D=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),_=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const C=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;I=C?vo(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:D,baseURL:_,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(R[0]),initTo:Number(R[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*D/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.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 Xo({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const r=this._findRef(e);if(r){if(i){this._isLastRef(r)&&e>=r.toTime&&(e=r.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),a=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:r.fromTime}this._appendVector[String(r.fromTime)]=t,this._stream.load(t,r.fromOffset,r.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=r.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const r=.1;if(s.toTime<i.to+r){const e=this._findRef(s.toTime);e&&e.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!a(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Zo;!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'}(Zo||(Zo={}));const td=[Zo.PAUSED,Zo.PLAYING];class ed{constructor(s){this.videoState=new Mn(Zo.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new ho,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&No(a.name))&&void 0!==s?s:On(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},h=a.fps;if(!n)continue;const u={id:t,quality:n,bitrate:o,size:d,fps:h};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(Zo.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return p(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)switch((null==s?void 0:s.to)!==P.PAUSED&&r.state===C.Requested&&td.includes(t)&&this.seek(r.position,r.forcePrecise),t){case Zo.STOPPED:return this.videoState.startTransitionTo(Zo.MANIFEST_LOADED),void this.prepare();case Zo.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Zo.INITIAL_REPRESENTATION_SELECTED);case Zo.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Zo.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Zo.METADATA_LOADED:return this.videoState.startTransitionTo(Zo.READY),void this.dash.updateRefsForCurrentTime();case Zo.READY:return void(i===P.PAUSED?(this.videoState.setState(Zo.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(Zo.PLAYING),this.playIfAllowed()));case Zo.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(Zo.PAUSED),this.video.pause()):(null==s?void 0:s.to)===P.PLAYING&&In(this.params.desiredState.playbackState,P.PLAYING));case Zo.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(Zo.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===P.PAUSED&&In(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}else t!==Zo.STOPPED&&(this.videoState.startTransitionTo(Zo.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(Zo.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=s,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=uo(s.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new po(this.video),this.dash=new Ko({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i,category:r.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:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',category:r.WTF,message:'DashProvider internal logic error',thrown:e})},o=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},h=fo(this.video),p=(t,e)=>this.subscription.add(t.subscribe(e,i));p(h.timeUpdate$,t.position$),p(h.durationChange$,t.duration$),p(h.ended$,t.endedEvent$),p(h.looped$,t.loopedEvent$),p(h.error$,t.error$),p(h.isBuffering$,t.isBuffering$),p(h.playing$,t.firstFrameEvent$),p(h.canplay$,t.canplay$),this.subscription.add(h.seeking$.subscribe((()=>{a(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===Zo.PLAYING||this.videoState.getState()===Zo.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(h.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(ro(this.video,e.isLooped,i)),this.subscription.add(ao(this.video,e.volume,h.volumeState$,i)),this.subscription.add(h.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(no(this.video,e.playbackRate,h.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),p(_o(this.video),this.elementSize$),this.subscription.add(h.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Zo.READY&&this.videoState.setState(Zo.READY)}),i)).add(h.pause$.subscribe((()=>{this.videoState.setState(Zo.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)}))).add(h.playing$.subscribe((()=>{this.videoState.setState(Zo.PLAYING),In(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(h.loadedMetadata$.subscribe((()=>{this.videoState.setState(Zo.METADATA_LOADED)}),i)).add(h.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,category:r.WTF,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(d(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$,n(this.video,'progress')).pipe(u((()=>{var t,e,i;const r=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),u=this.elementSize$.getValue(),l=o();let c;if(n&&this.params.desiredState.autoVideoTrackSwitching.setState(n.to),!l&&s(d))c=d;else{const i=jo(this.video.buffered,1e3*this.video.currentTime),s=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,n=Math.min(i/s,1);c=null===(e=Ro(a.map((({track:t})=>t)),{container:u,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:n,playbackRate:this.video.playbackRate,current:null===(t=a.find((({representation:t})=>t===r)))||void 0===t?void 0:t.track}))||void 0===e?void 0:e.id}return s(c)?null===(i=a.find((({track:t})=>t.id===c)))||void 0===i?void 0:i.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(v({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(b((t=>t.to===Zo.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(b(s))}).pipe(g()).subscribe((()=>this.videoState.setState(Zo.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(b(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&o()?t.height<=e.height:t===e))).subscribe((t=>{const e=jo(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!o())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Do(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Wo(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(g(),S(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(b(s)).subscribe(this.handleRepresentationPlay,i)).add(d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return o(t)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Oo(this.video).then((t=>{t||(this.videoState.setState(Zo.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var id,sd,rd,ad,nd;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(id||(id={})),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'}(sd||(sd={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(rd||(rd={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(ad||(ad={})),function(t){t.MP4='mp4',t.WEBM='webm'}(nd||(nd={}));var od=(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 dd='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 hd,ud;let ld=!1;try{ld=co()&&parseInt(null!==(ud=null===(hd=navigator.userAgent.match(/Version\/(\d+)/))||void 0===hd?void 0:hd[1])&&void 0!==ud?ud:'',10)<16}catch(t){console.error(t)}class cd{constructor(t){this.bufferFull$=new e,this.error$=new e,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',category:r.VIDEO_PIPELINE,message:'Buffer appending or removal failed',thrown:t})}},this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const r={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(r),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ld&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var t;if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===i?this.bufferFull$.next(this.currentTask.data.byteLength):t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===i||this.error$.next({id:`BufferTaskQueue:${i}`,category:r.VIDEO_PIPELINE,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:e}=t;switch(e){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(t.init);break;default:o(e)}}}var pd,md=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'}(pd||(pd={}));class fd{constructor({throughputEstimator:e,requestQuic:s}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new Wn,this.subscription=new i,this.fetchManifest=E(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=eo(e));const i=yield Qn(e,{signal:this.abortAllController.signal}).catch(vd);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetch=E(this.abortAllController.signal,async function*(t,{rangeMethod:e=pd.HEADER,range:i,onProgress:s,priority:r='auto',signal:a,measureThroughput:h=!0}={}){var u,l,c,p;let m=t;const f=new Headers;if(i)switch(e){case pd.HEADER:f.append('Range',`${i.from}-${i.to}`);break;case pd.PARAM:{const t=new URL(m,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),m=t.toString();break}default:o(e)}this.requestQuic&&(m=eo(m));let v=this.abortAllController.signal;if(a){const t=new Wn;if(this.subscription.add(d(n(this.abortAllController.signal,'abort'),n(a,'abort')).subscribe((()=>{try{t.abort()}catch(t){vd(t)}}))),this.abortAllController.signal.aborted||a.aborted)try{t.abort()}catch(t){vd(t)}v=t.signal}const g=y(),S=yield Qn(m,{priority:r,headers:f,signal:v}).catch(vd),b=y();if(null===(u=this.throughputEstimator)||void 0===u||u.addRawRtt(b-g),!S)return null;if(!S.ok||!S.body)return Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));this.onHeadersReceived(S.headers);const T=parseInt(null!==(l=S.headers.get('Content-Length'))&&void 0!==l?l:'',10)||i&&i.to-i.from+1||NaN;if(!T){const t=yield S.arrayBuffer();return null===(c=this.throughputEstimator)||void 0===c||c.addRawSpeed(t.byteLength,y()-b),null==s||s(new DataView(t),t.byteLength),t}if(!s&&!h)return S.arrayBuffer();const[w,$]=S.body.tee(),k=w.getReader();h&&(null===(p=this.throughputEstimator)||void 0===p||p.trackStream($));let A=0;const P=new ArrayBuffer(T),R=new Uint8Array(P),D=new DataView(P);let _=!1;const I=t=>{_=!0,vd(t)},C=E(v,async function*({done:t,value:e}){0===A&&this.lastRequestFirstBytes$.next(y()-g),v.aborted||(t?null==s||s(D,A):e&&(R.set(e,A),A+=e.byteLength,null==s||s(D,A),yield null==k?void 0:k.read().then(C,I)))}.bind(this));return yield null==k?void 0:k.read().then(C,I),_?null:P}.bind(this)),this.fetchByteRangeRepresentation=E(this.abortAllController.signal,async function*(t,e,i){if(t.type!==rd.BYTE_RANGE)return null;const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,h=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,h=r+1===a,h&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0);const u=yield this.fetch(t.url,{rangeMethod:pd.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!u)return null;const l=new DataView(u,s-o,r-o+1);if(!e.validateData(l))throw new Error('Invalid media file');const c=e.parseInit(l);let p;if(h&&void 0!==a&&void 0!==n)p=new DataView(u,a-o,n-a+1);else{const s=e.getIndexRange(c);if(s){const e=yield this.fetch(t.url,{rangeMethod:pd.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,c);return{dataView:new DataView(u),segments:m}}.bind(this)),this.fetchTemplateRepresentation=E(this.abortAllController.signal,async function*(t,e){if(t.type!==rd.TEMPLATE)return null;const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield this.fetch(i,{priority:e,measureThroughput:!1});if(!s)return null;return{segments:t.segments.map((t=>({...t,status:ad.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=s}onHeadersReceived(t){const{type:e,reused:i}=Wo(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchRepresentation(t,e,i='auto'){var s,r;const{type:a}=t;switch(a){case rd.BYTE_RANGE:return null!==(s=await this.fetchByteRangeRepresentation(t,e,i))&&void 0!==s?s:null;case rd.TEMPLATE:return null!==(r=await this.fetchTemplateRepresentation(t,i))&&void 0!==r?r:null;default:o(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const vd=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},gd=new TextDecoder('ascii'),Sd=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=gd.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)}},bd={validateData:t=>'ftyp'===gd.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Sd(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=4294967295&r();let h=n/a*1e3,u=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:ad.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=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=Sd(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 yd,Td;!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'}(yd||(yd={})),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'}(Td||(Td={}));const Ed={[yd.EBML]:{type:Td.Master},[yd.EBMLVersion]:{type:Td.UnsignedInteger},[yd.EBMLReadVersion]:{type:Td.UnsignedInteger},[yd.EBMLMaxIDLength]:{type:Td.UnsignedInteger},[yd.EBMLMaxSizeLength]:{type:Td.UnsignedInteger},[yd.DocType]:{type:Td.String},[yd.DocTypeVersion]:{type:Td.UnsignedInteger},[yd.DocTypeReadVersion]:{type:Td.UnsignedInteger},[yd.Void]:{type:Td.Binary},[yd.Segment]:{type:Td.Master},[yd.SeekHead]:{type:Td.Master},[yd.Seek]:{type:Td.Master},[yd.SeekID]:{type:Td.Binary},[yd.SeekPosition]:{type:Td.UnsignedInteger},[yd.Info]:{type:Td.Master},[yd.TimestampScale]:{type:Td.UnsignedInteger},[yd.Duration]:{type:Td.Float},[yd.Tracks]:{type:Td.Master},[yd.Chapters]:{type:Td.Master},[yd.Cluster]:{type:Td.Master},[yd.Timestamp]:{type:Td.UnsignedInteger},[yd.SilentTracks]:{type:Td.Master},[yd.SilentTrackNumber]:{type:Td.UnsignedInteger},[yd.Position]:{type:Td.UnsignedInteger},[yd.PrevSize]:{type:Td.UnsignedInteger},[yd.SimpleBlock]:{type:Td.Binary},[yd.BlockGroup]:{type:Td.Master},[yd.EncryptedBlock]:{type:Td.Binary},[yd.Attachments]:{type:Td.Master},[yd.Tags]:{type:Td.Master},[yd.Cues]:{type:Td.Master},[yd.CuePoint]:{type:Td.Master},[yd.CueTime]:{type:Td.UnsignedInteger},[yd.CueTrackPositions]:{type:Td.Master},[yd.CueTrack]:{type:Td.UnsignedInteger},[yd.CueClusterPosition]:{type:Td.UnsignedInteger},[yd.CueRelativePosition]:{type:Td.UnsignedInteger},[yd.CueDuration]:{type:Td.UnsignedInteger},[yd.CueBlockNumber]:{type:Td.UnsignedInteger},[yd.CueCodecState]:{type:Td.UnsignedInteger},[yd.CueReference]:{type:Td.Master},[yd.CueRefTime]:{type:Td.UnsignedInteger}},wd=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=$d(t,i),r=s in Ed,a=r?Ed[s].type:Td.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+$d(d),u=i+o;let l;return l=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:u,tagSize:u+h,value:l,valueSize:h}},$d=(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},kd=(t,e)=>{switch(e){case Td.SignedInteger:return t.getInt8(0);case Td.UnsignedInteger:return $d(t);case Td.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Td.String:return new TextDecoder('ascii').decode(t);case Td.UTF8:return new TextDecoder('utf-8').decode(t);case Td.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Td.Master:case Td.Binary:return t;default:o(e)}},Ad=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=wd(s);if(!e(r))return;r.type===Td.Master&&Ad(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Pd=[yd.Info,yd.SeekHead,yd.Tracks,yd.Chapters,yd.Cluster,yd.Cues,yd.Attachments,yd.Tags],Rd=[yd.Timestamp,yd.SilentTracks,yd.SilentTrackNumber,yd.Position,yd.PrevSize,yd.SimpleBlock,yd.BlockGroup,yd.EncryptedBlock],Dd={validateData:t=>{if(t.getUint32(0)!==yd.EBML)return!1;let e,i,s;const r=wd(t);return Ad(r.value,(({tag:t,type:r,value:a})=>(t===yd.EBMLReadVersion?e=kd(a,r):t===yd.DocType?i=kd(a,r):t===yd.DocTypeReadVersion&&(s=kd(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,h=!1;return Ad(t,(({tag:t,type:u,value:l,valueSize:c})=>{if(t===yd.SeekID){const t=kd(l,u);n=$d(t)}else t!==yd.SeekPosition&&(n=void 0);return t===yd.Segment?(e=l.byteOffset,i=l.byteOffset+c):t===yd.Info?o=!0:t===yd.SeekHead?d=!0:t===yd.TimestampScale?s=kd(l,u):t===yd.Duration?r=kd(l,u):t===yd.SeekPosition&&n===yd.Cues?a=kd(l,u):o&&d&&Pd.includes(t)&&(h=!0),!h})),p(e,'Failed to parse webm Segment start'),p(i,'Failed to parse webm Segment end'),p(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},getIndexRange:t=>{if(a(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return Ad(t,(({tag:t,type:e,value:s})=>{switch(t){case yd.Cues:i=!0;break;case yd.CuePoint:o&&a(o)&&n.push(o),o={};break;case yd.CueTime:o&&(o.time=kd(s,e));break;case yd.CueTrackPositions:break;case yd.CueClusterPosition:o&&(o.position=kd(s,e));break;default:i&&Pd.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:ad.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Ad(t,(s=>s.tag===yd.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Rd.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[yd.SimpleBlock,yd.BlockGroup,yd.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class _d{constructor(d,h,u,l,{fetcher:c,tuning:m,getCurrentPosition:f}){switch(this.onLastSegment$=new t(!1),this.fullyBuffered$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.gaps=[],this.subscription=new i,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Wn,this.destroyAbortController=new Wn,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=E(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);p(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new cd(this.sourceBuffer),this.subscription.add(n(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',category:r.WTF,message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(n(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',category:r.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,md(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(e,'high',!0);const i=this.initData.get(e.id),a=this.segments.get(e.id);if(p(i,'No init buffer for starting representation'),p(a,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let o=0;for(const t of a)t.time.from-o>0&&this.gaps.push({representation:e.id,from:o,to:t.time.from}),o=t.time.to;s(e.duration)&&e.duration-o>0&&this.gaps.push({representation:e.id,from:o,to:e.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=E(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const e=this.representations.get(t);p(e,`No such representation ${t}`);let i=this.initData.get(t);if(a(i)?yield this.loadInit(e,'high',!1):i instanceof Promise&&(yield i),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal);const r=this.getCurrentPosition();s(r)&&this.maintain(r)}.bind(this)),this.fetcher=c,this.tuning=m,this.forwardBufferTarget=m.dash.forwardBufferTargetAuto,this.getCurrentPosition=f,this.container=u,u){case nd.MP4:this.containerParser=bd;break;case nd.WEBM:this.containerParser=Dd;break;default:o(u)}this.initData=new Map(l.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(l.map((t=>[t.id,t]))),this.kind=d,this.mediaSource=h,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Wn,this.abortBuffer()}maintain(t){if(a(this.downloadingRepresentationId)||a(this.playingRepresentationId)||a(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(p(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let r=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=jo(this.sourceBuffer.buffered,t),a=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(r=a)}if(isFinite(this.bufferLimit)&&md(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),s&&s.status!==ad.NONE))return;let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,e.segmentReference.type,r),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=yo(n,0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===ad.FED&&!n.length&&jo(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=yo(i,-1);o&&o.status===ad.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){var e,i,s;const r=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!r)return;const a=this.segments.get(r);if(!a)return;const n=a.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===ad.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==rd.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!==ad.NONE&&e.status!==ad.PARTIALLY_EJECTED)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,a,n=t;const{type:d}=e.segmentReference;switch(d){case rd.BYTE_RANGE:s=e.segmentReference.url,a={from:yo(t,0).byte.from,to:yo(t,-1).byte.to};break;case rd.TEMPLATE:{const i=yo(t,0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),n=[i];break}default:o(d)}for(const t of n)t.status=ad.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:e.id});const{signal:h}=this.downloadAbortController;if(this.failedDownloads&&(await E(h,async function*(){const t=w(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),h.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:pd.PARAM,range:a,onProgress:(t,i)=>{if(!h.aborted)try{this.onSomeDataLoaded(t,e.id,a?a.from:0,i,h)}catch(t){this.error$.next({id:'SegmentFeeding',category:r.VIDEO_PIPELINE,message:'Error when feeding segments',thrown:t})}},signal:h,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}onSegmentDownloadError(t){var e;let i=!1;const a=this.getCurrentPosition();if(this.sourceBuffer&&s(a)){i=jo(null===(e=this.sourceBuffer)||void 0===e?void 0:e.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,i||this.error$.next({id:'SegmentDownload',category:r.NETWORK,message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,r){if(!this.activeSegments.size)return;const a=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=ad.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===ad.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=ad.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,h=t.byteLength;for(const o of this.activeSegments){const{segment:u}=o,l=d===rd.BYTE_RANGE,c=l?u.byte.to-u.byte.from+1:h;if(o.representationId!==e)continue;if(!(!l||u.byte.from>=i&&u.byte.to<i+t.byteLength))continue;if(r.aborted){a(o);continue}const p=l?u.byte.from-i:0,m=p<s,f=(l?u.byte.to-i:t.byteLength)<=s;if(u.status===ad.DOWNLOADING&&m&&f){u.status=ad.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,c);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(c,s-p),o.loadedBytes>o.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),i=o.loadedBytes===c?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(u.status=ad.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===c&&n(o);else{if(o.feedingBytes<c)return;a(o)}})))}}}abortSegment(t){t.status===ad.PARTIALLY_FED||t.status===ad.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=ad.NONE)),t.status=ad.PARTIALLY_EJECTED):t.status=ad.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=dd((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,e='auto',i=!1){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',a=(!i&&this.failedDownloads>0?E(this.destroyAbortController.signal,async function*(){const t=w(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s))).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,r),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',category:r.WTF,message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,a),a}async pruneBuffer(t){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,r=1/0,n=-1/0,o=!1;const d=t=>{var e;r=Math.min(r,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;s+=i};for(const r of i){if(r.time.to>=e||s>=t)break;r.status===ad.FED&&d(r)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const r of i){if(r.time.from<e+this.forwardBufferTarget||s>t)break;r.status===ad.FED&&d(r)}}if(o=isFinite(r)&&isFinite(n),!o)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);for(const t of i)if(t.status===ad.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(s)){r=e,n=s;break}}return o=isFinite(r)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(r,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(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=dd((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',category:r.WTF,message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(a(this.sourceBuffer)||a(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(e)),s=Math.round(1e3*this.sourceBuffer.buffered.end(e));t.push({from:i,to:s})}for(const e of this.segments.values())for(const i of e){const{status:e}=i;if(e!==ad.FED&&e!==ad.PARTIALLY_EJECTED)continue;const s=Math.floor(i.time.from),r=Math.ceil(i.time.to),a=t.some((t=>t.from-1<=s&&t.to+1>=r)),n=t.some((t=>s>=t.from-1&&s<=t.to+1||r>=t.from-1&&r<=t.to+1));a||(i.status=n?ad.PARTIALLY_EJECTED:ad.NONE)}}}const Id=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)},Cd=(t,e)=>{let i=t;i=i.replaceAll('$$','$');const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[t,e]of Object.entries(s)){const s=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(s,((t,i)=>a(e)?t:a(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Ld=['timeupdate','progress','play','seeked','stalled'];var xd,Nd;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(xd||(xd={}));class Od{constructor(a){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new Mn(xd.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.gapWatchdogStarted=!1,this.destroyController=new Wn,this.initManifest=E(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(xd.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',category:r.NETWORK,message:'Failed to load manifest',thrown:t})));if(!i)return null;let a;try{a=((t,e)=>{var i,r,a,n,o,d,h,u,l,c,p,m,f,v,g,S,b,y,T,E,w,$,k,A,P,R,D,_,I,C,L,x,N,O,B;const M={video:[],audio:[],text:[]},U=(new DOMParser).parseFromString(t,'application/xml').children[0],V=U.getElementsByTagName('Period')[0],F=V.children;let q;const H=U.getAttribute('mediaPresentationDuration'),G=V.getAttribute('duration');if(H)q=Id(H);else if(G){const t=Id(G);s(t)&&(q=t)}let Y=0;const z=null!==(r=null===(i=U.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==r?r:[],Q=z.includes(sd.WEBM_AS_IN_FFMPEG)||z.includes(sd.WEBM_AS_IN_SPEC)?nd.WEBM:nd.MP4;for(const t of F){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==i?void 0:i.split('/')[0],U=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],V=t.querySelectorAll('Representation');if('text'!==r)for(const a of V){const n=null!==(d=a.getAttribute('mimeType'))&&void 0!==d?d:i,o=null!==(u=null!==(h=a.getAttribute('codecs'))&&void 0!==h?h:s)&&void 0!==u?u:'',V=null!==(c=null!==(l=a.getAttribute('contentType'))&&void 0!==l?l:null==n?void 0:n.split('/')[0])&&void 0!==c?c:r,F=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],H=parseInt(null!==(f=a.getAttribute('width'))&&void 0!==f?f:'',10),G=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),Q=parseInt(null!==(g=a.getAttribute('bandwidth'))&&void 0!==g?g:'',10)/1e3,W=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',j=null!==(b=a.getAttribute('quality'))&&void 0!==b?b:void 0,J=W?vo(W):void 0,X=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(Y++).toString(10)}@${'video'===V?`${G}p`:'audio'===V?`${Q}Kbps`:o}`,K=null!==(w=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==w?w:'',Z=new URL(K,e).toString(),tt=[...z,...U,...F];let et;const it=a.querySelector('SegmentBase'),st=a.querySelector('SegmentTemplate');if(it){const t=null!==(k=null===($=a.querySelector('SegmentBase Initialization'))||void 0===$?void 0:$.getAttribute('range'))&&void 0!==k?k:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},r=null===(A=a.querySelector('SegmentBase'))||void 0===A?void 0:A.getAttribute('indexRange'),[n,o]=r?r.split('-').map((t=>parseInt(t,10))):[],d=r?{from:n,to:o}:void 0;et={type:rd.BYTE_RANGE,url:Z,initRange:s,indexRange:d}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(P=a.getAttribute('id'))&&void 0!==P?P:void 0,bandwidth:null!==(R=a.getAttribute('bandwidth'))&&void 0!==R?R:void 0},e=parseInt(null!==(D=st.getAttribute('timescale'))&&void 0!==D?D:'',10),i=null!==(_=st.getAttribute('initialization'))&&void 0!==_?_:'',s=st.getAttribute('media'),r=null!==(C=parseInt(null!==(I=st.getAttribute('startNumber'))&&void 0!==I?I:'',10))&&void 0!==C?C:1,n=Cd(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(L=st.querySelectorAll('SegmentTimeline S'))&&void 0!==L?L:[],d=[];let h=r,u=0;for(const i of o){const r=1e3*parseInt(null!==(x=i.getAttribute('d'))&&void 0!==x?x:'',10),a=parseInt(null!==(N=i.getAttribute('r'))&&void 0!==N?N:'',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=Cd(s,{...t,segmentNumber:h.toString(10),segmentTime:n.toString(10)}),a=n?n/e:u;u+=r/e;const o=u;h++,d.push({time:{from:a,to:o},url:i})}}et={type:rd.TEMPLATE,baseUrl:Z,initUrl:n,segments:d}}}if(!V||!n)continue;const rt={video:id.VIDEO,audio:id.AUDIO,text:id.TEXT}[V];rt&&M[rt].push({id:X,kind:rt,segmentReference:et,profiles:tt,duration:q,bitrate:Q,mime:n,codecs:o,width:H,height:G,fps:J,quality:j})}}return{duration:q,container:Q,representations:M}})(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',category:r.PARSER,message:'Failed to parse MPD manifest',thrown:t})}if(!a)return null;const n=({mime:e,codecs:i})=>{var s,r,a;return Boolean((null===(s=t.canPlayType)||void 0===s?void 0:s.call(t,e))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${e}; codecs="${i}"`)))};return this.manifest={...a,representations:Rn(Object.entries(a.representations).map((([t,e])=>[t,e.filter(n)])))},this.manifest.representations.video.length?this.state$.setState(xd.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',category:r.PARSER,message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=E(this.destroyController.signal,async function*(t,e){p(this.manifest),p(this.element),this.state$.startTransitionTo(xd.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new _d(id.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new _d(id.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=d(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),o=d(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(d(this.forceEnded$,v({allBuffersFull:a,someBufferEnded:o}).pipe(b((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var t;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',category:r.VIDEO_PIPELINE,message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(d(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)}))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)]):yield this.videoBufferManager.startWith(t),this.state$.setState(xd.REPRESENTATION_SELECTED),p(this.element),this.subscription.add(d(...Ld.map((t=>n(this.element,t))),n(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',category:r.WTF,message:'Internal logic error',thrown:t})}))),this.subscription.add(n(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(n(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&od(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this)),this.tick=()=>{var t,e;if(!this.element||!this.videoBufferManager)return;const i=1e3*this.element.currentTime;this.videoBufferManager.maintain(i),null===(t=this.audioBufferManager)||void 0===t||t.maintain(i),!this.videoBufferManager.gaps.length&&!(null===(e=this.audioBufferManager)||void 0===e?void 0:e.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=$(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',category:r.WTF,message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=a.throughputEstimator,this.tuning=a.tuning,this.fetcher=new fd({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(t,e){const i={[id.VIDEO]:this.videoBufferManager,[id.AUDIO]:this.audioBufferManager,[id.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}seek(t,e){var i,s,r,a,n;let o;p(this.element),p(this.videoBufferManager),o=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(null!==(i=this.videoBufferManager.findSegmentStartTime(t))&&void 0!==i?i:t,null!==(r=null===(s=this.audioBufferManager)||void 0===s?void 0:s.findSegmentStartTime(t))&&void 0!==r?r:t),od(this.element.buffered,o)||(this.videoBufferManager.abort(),null===(a=this.audioBufferManager)||void 0===a||a.abort()),this.videoBufferManager.maintain(o),null===(n=this.audioBufferManager)||void 0===n||n.maintain(o),this.element.currentTime=o/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(xd.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'}(Nd||(Nd={}));const Bd=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?No(a):void 0)&&void 0!==n?n:On({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},Md=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=yo(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:yo(t,-1)};class Ud{constructor(e){this.subscription=new i,this.videoState=new Mn(Nd.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new ho,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Po,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===C.Requested&&(null==i?void 0:i.to)!==P.PAUSED&&t!==Nd.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===Nd.STOPPED)return this.videoState.startTransitionTo(Nd.READY),void this.prepare();switch(t){case Nd.READY:return void(e===P.PAUSED?(this.videoState.setState(Nd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Nd.PLAYING),this.playIfAllowed()));case Nd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Nd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&In(this.params.desiredState.playbackState,P.PLAYING));case Nd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Nd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&In(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}else t!==Nd.STOPPED&&(this.videoState.startTransitionTo(Nd.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(Nd.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=e,this.video=uo(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Do(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Od({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=fo(this.video),a=e=>{t.error$.next({id:'DashVKProvider',category:r.WTF,message:'DashVKProvider internal logic error',thrown:e})},o=(t,e)=>this.subscription.add(t.subscribe(e,a));o(i.timeUpdate$,t.position$),o(i.durationChange$,t.duration$),o(i.ended$,t.endedEvent$),o(i.looped$,t.loopedEvent$),o(i.error$,t.error$),o(i.isBuffering$,t.isBuffering$),o(i.currentBuffer$,t.currentBuffer$),o(i.playing$,t.firstFrameEvent$),o(i.canplay$,t.canplay$),o(this.player.error$,t.error$),o(this.player.lastConnectionType$,t.httpConnectionType$),o(this.player.lastConnectionReused$,t.httpConnectionReused$),o(this.player.lastRequestFirstBytes$.pipe(b(s),g(),S(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,a)),this.subscription.add(ro(this.video,e.isLooped,a)),this.subscription.add(ao(this.video,e.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(no(this.video,e.playbackRate,i.playbackRateState$,a)),o(_o(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Nd.PLAYING),In(e.playbackState,P.PLAYING)}),a)).add(i.pause$.subscribe((()=>{this.videoState.setState(Nd.PAUSED),In(e.playbackState,P.PAUSED)}),a)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Nd.PLAYING&&this.playIfAllowed()}),a)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(b((({to:t})=>t===xd.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Nd.READY)})));const h=e=>t.error$.next({id:'RepresentationSwitch',category:r.WTF,message:'Switching representations threw',thrown:e});this.subscription.add(d(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,n(this.video,'progress')).subscribe((()=>{var i,s,r,a,n,o,d,u;const l=this.player.state$.getState(),c=this.player.state$.getTransition();if(l===xd.NONE||!this.videoTracks.length)return;const m=l===xd.MANIFEST_LOADED&&!c,f=l===xd.REPRESENTATION_SELECTED&&!c,v=e.autoVideoTrackSwitching.getState(),g=e.videoTrack.getState(),S=null===(i=this.videoTracks.find((({track:{id:t}})=>t===g)))||void 0===i?void 0:i.track,b=t.currentVideoTrack$.getValue(),y=jo(this.video.buffered,1e3*this.video.currentTime),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),w=Math.max(S&&!v&&null!==(r=null===(s=this.audioRepresentations.get(S.id))||void 0===s?void 0:s.bitrate)&&void 0!==r?r:0,b&&null!==(n=null===(a=this.audioRepresentations.get(b.id))||void 0===a?void 0:a.bitrate)&&void 0!==n?n:0),$=Ro(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:w,forwardBufferHealth:E,current:b,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),k=v?null!=$?$:S:null!=S?S:$;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),m){const t=k&&(null===(o=this.videoTracks.find((({track:t})=>t===k)))||void 0===o?void 0:o.representation);p(t),this.player.initRepresentations(t.id,null===(d=this.audioRepresentations.get(t.id))||void 0===d?void 0:d.id)}else if(f){const t=k&&(null===(u=this.videoTracks.find((({track:t})=>t===k)))||void 0===u?void 0:u.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(id.VIDEO,t.id).catch(h),e&&this.player.switchRepresentation(id.AUDIO,e.id).catch(h)}}}),a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,e,t);const f=d(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0));this.subscription.add(f.subscribe(this.syncPlayback,a))}async prepare(){const t=await 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=Bd(t);if(s){this.videoTracks.push({track:s,representation:t});const r=Md(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(){Oo(this.video).then((t=>{t||(this.videoState.setState(Nd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Vd={};var Fd;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Fd||(Fd={}));const qd=(t,e)=>new T((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class Hd{constructor(t){this.subscription=new i,this.videoState=new Mn(Fd.INITIALIZING),this.textTracksManager=new ho,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==Fd.INITIALIZING)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Fd.STOPPED:break;case Fd.READY:case Fd.PLAYING:case Fd.PAUSED:this.stop();break;default:o(t)}break;case P.PLAYING:switch(t){case Fd.PLAYING:break;case Fd.STOPPED:this.prepare();break;case Fd.READY:case Fd.PAUSED:this.playIfAllowed();break;default:o(t)}break;case P.PAUSED:switch(t){case Fd.PAUSED:break;case Fd.STOPPED:this.prepare();break;case Fd.READY:this.videoState.setState(Fd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED);break;case Fd.PLAYING:this.pause();break;default:o(t)}break;default:o(e)}},this.video=uo(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Do(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',category:r.NETWORK,message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Vd.Hls=e.default,Vd.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){p(Vd.Hls,'hls.js not loaded'),this.hls=new Vd.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Fd.STOPPED)}subscribe(){p(Vd.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',category:r.WTF,message:'HlsJsProvider internal logic error',thrown:t})},n=fo(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,i));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.currentBuffer$,e.currentBuffer$),o(n.loadStart$,e.firstBytesEvent$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.seeked$,e.seekedEvent$),this.subscription.add(ro(this.video,t.isLooped,i)),this.subscription.add(ao(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(no(this.video,t.playbackRate,n.playbackRateState$,i)),this.subscription.add(qd(this.hls,Vd.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),category:r.WTF,message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(n.playing$.subscribe((()=>{this.videoState.setState(Fd.PLAYING),In(t.playbackState,P.PLAYING)}),i)).add(n.pause$.subscribe((()=>{this.videoState.setState(Fd.PAUSED),In(t.playbackState,P.PAUSED)}),i)).add(n.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Fd.READY&&this.videoState.setState(Fd.READY),this.videoState.getState()===Fd.PLAYING&&this.playIfAllowed()}),i)),o(qd(this.hls,Vd.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=No(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:On({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,h={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:h,level:e}),t.push(h),t}),[])))),e.availableVideoTracks$),o(qd(this.hls,Vd.Events.LEVEL_LOADING).pipe(u((({url:t})=>Do(t)))),e.hostname$),this.subscription.add(so(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const h=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},c=qd(this.hls,Vd.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>h(this.hls.levels[t]))));c.pipe(b(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(so(t.videoTrack,(()=>{var t;return null===(t=h(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(a(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),r=this.hls.currentLevel,n=this.hls.levels[r];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:c.pipe(u((t=>null==t?void 0:t.id))),onError:i})),o(n.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const f=d(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0));this.subscription.add(f.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Fd.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Fd.PLAYING);await Oo(this.video)||(this.videoState.setState(Fd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Fd.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(Fd.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0)}}var Gd=async t=>{const e=await Qn(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const Yd=t=>{let e=null;if(t.QUALITY&&(e=No(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=On({width:i,height:s})}return null!=e?e:null},zd=async(t,e=t)=>{var i;const s=await Qn(t),r=(await 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=Rn(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=Yd(n);let h;n.BANDWIDTH&&(h=parseInt(n.BANDWIDTH,10)/1e3||void 0),!h&&n['AVERAGE-BANDWIDTH']&&(h=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const u=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let l;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(l={width:t,height:e})}const c=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:c,bandwidth:h,size:l,fps:u})}return a};var Qd,Wd,jd;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Qd||(Qd={}));class Jd{constructor(e){var s;this.subscription=new i,this.videoState=new Mn(Qd.STOPPED),this.textTracksManager=new ho,this.manifests$=new t([]),this.liveOffset=new lo,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Qd.STOPPED&&(this.videoState.startTransitionTo(Qd.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(Qd.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Qd.STOPPED)return this.videoState.startTransitionTo(Qd.READY),void this.prepare();if(s||r){const t=this.videoState.getState();return this.videoState.setState(Qd.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested)return this.videoState.startTransitionTo(Qd.READY),this.seek(a.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Qd.READY:return void(e===P.PAUSED?(this.videoState.setState(Qd.PAUSED),this.liveOffset.pause(),In(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qd.PLAYING),this.playIfAllowed()));case Qd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qd.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&In(this.params.desiredState.playbackState,P.PLAYING));case Qd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qd.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(null==i?void 0:i.to)===P.PAUSED&&(In(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Qd.CHANGING_MANIFEST:break;default:return o(t)}},this.params=e,this.video=uo(e.container),this.params.output.element$.next(this.video);const a={id:'master',quality:Dn.INVARIANT,url:this.params.source.url};this.manifests$.next([a]),zd(_n(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([a,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',category:r.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Do(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(s=e.source.maxSeekBackTime)&&void 0!==s?s:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',category:r.WTF,message:'HlsLiveProvider internal logic error',thrown:e})},a=fo(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(a.ended$,t.endedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadedMetadata$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(ao(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(no(this.video,e.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Qd.PLAYING),In(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Qd.PAUSED),In(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Qd.READY&&this.videoState.setState(Qd.READY),this.videoState.getState()===Qd.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),u((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Do(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Qd.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(a.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)}),i)),this.subscription.add(v({startTime:this.manifestStartTime$.pipe(b(s)),currentTime:a.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,l(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(a(t))return;const e=_n(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),Gd(e).then((t=>{var i;if(a(t)){const t=null!==(i=this.params.source.maxSeekBackTime)&&void 0!==i?i:this.maxSeekBackTime$.getValue();if(a(t)||!isFinite(t))try{Qn(e).then((t=>t.text())).then((t=>{var i;const s=null===(i=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(t))||void 0===i?void 0:i[1];if(s){const t=new URL(s,e).toString();Gd(t).then((t=>{a(t)||this.maxSeekBackTime$.next(t)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Oo(this.video).then((t=>{t||(this.videoState.setState(Qd.PAUSED),this.liveOffset.pause(),In(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Wd||(Wd={}));class Xd{constructor(e){this.subscription=new i,this.videoState=new Mn(Wd.STOPPED),this.textTracksManager=new ho,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Wd.STOPPED&&(this.videoState.startTransitionTo(Wd.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(Wd.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Wd.STOPPED)return this.videoState.startTransitionTo(Wd.READY),void this.prepare();if(s||r){const t=this.videoState.getState();this.videoState.setState(Wd.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case Wd.READY:return void(e===P.PAUSED?(this.videoState.setState(Wd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Wd.PLAYING),this.playIfAllowed()));case Wd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Wd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&In(this.params.desiredState.playbackState,P.PLAYING));case Wd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Wd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&In(this.params.desiredState.playbackState,P.PAUSED));case Wd.CHANGING_MANIFEST:break;default:return o(t)}},this.params=e,this.video=uo(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:Dn.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Do(this.params.source.url)),zd(this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',category:r.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',category:r.WTF,message:'HlsProvider internal logic error',thrown:e})},a=fo(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadedMetadata$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),this.subscription.add(ro(this.video,e.isLooped,i)),this.subscription.add(ao(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(no(this.video,e.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Wd.PLAYING),In(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Wd.PAUSED),In(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Wd.READY&&this.videoState.setState(Wd.READY),this.videoState.getState()===Wd.PLAYING&&this.playIfAllowed()}),i).add(a.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Do(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Wd.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===C.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();a(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Oo(this.video).then((t=>{t||(this.videoState.setState(Wd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(jd||(jd={}));class Kd{constructor(t){this.subscription=new i,this.videoState=new Mn(jd.STOPPED),this.trackUrls={},this.textTracksManager=new ho,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==jd.STOPPED&&(this.videoState.startTransitionTo(jd.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(jd.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(t===jd.STOPPED)return this.videoState.startTransitionTo(jd.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case jd.READY:return void(e===P.PAUSED?(this.videoState.setState(jd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(jd.PLAYING),this.playIfAllowed()));case jd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(jd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&In(this.params.desiredState.playbackState,P.PLAYING));case jd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(jd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&In(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}},this.params=t,this.video=uo(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',category:r.WTF,message:'MpegProvider internal logic error',thrown:e})},a=fo(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadedMetadata$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),this.subscription.add(ro(this.video,e.isLooped,i)),this.subscription.add(ao(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(no(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(jd.PLAYING),In(e.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(jd.PAUSED),In(e.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===jd.READY&&this.videoState.setState(jd.READY);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===jd.PLAYING&&this.playIfAllowed()}),i)),this.textTracksManager.connect(this.video,e,t);const o=d(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();p(i,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[i];p(s,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(s=eo(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(Do(s))}playIfAllowed(){Oo(this.video).then((t=>{t||(this.videoState.setState(jd.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}const Zd=['stun:videostun.mycdn.me:80'],th=()=>null;class eh{constructor(t,e){this.ws=null,this.peerConnection=null,this.serverUrl='',this.streamKey='',this.stream=null,this.signalingType='JOIN',this.retryCount=0,this.externalStartCallback=th,this.externalStopCallback=th,this.externalErrorCallback=th,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()}}async handleUpdateMessage(t){try{const e=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(e),this.handleAnswer(t.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const t={iceServers:[{urls:Zd}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(e),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:e.sdp,callSupport:!1})}catch(t){this.handleRTCError(t)}}async handleAnswer(t){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:t}))}catch(t){this.handleRTCError(t)}}async handleCandidate(t){if(t)try{this.peerConnection&&await this.peerConnection.addIceCandidate(t)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(t){this.handleRTCError(t)}}handleSystemError(t){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',category:r.WTF,message:t.message})}async onPeerConnectionStream(t){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()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const t=await 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:Zd,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var ih,sh,rh,ah,nh,oh,dh,hh,uh,lh,ch,ph,mh,fh,vh,gh,Sh,bh;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ih||(ih={}));class yh{constructor(e){this.videoState=new Mn(ih.STOPPED),this.maxSeekBackTime$=new t(0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==ih.STOPPED&&(this.videoState.startTransitionTo(ih.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(ih.STOPPED),In(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition();if(t===ih.STOPPED)return this.videoState.startTransitionTo(ih.READY),void this.prepare();if(s)this.prepare();else switch(t){case ih.READY:return void(e===P.PAUSED?(this.videoState.setState(ih.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ih.PLAYING),this.playIfAllowed()));case ih.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ih.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&In(this.params.desiredState.playbackState,P.PLAYING));case ih.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ih.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&In(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}},this.subscription=new i,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=uo(e.container),this.liveStreamClient=new eh(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:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'WebRTCLiveProvider',category:r.WTF,message:'WebRTCLiveProvider internal logic error',thrown:e})};d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})}));const s=fo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(s.timeUpdate$,t.liveTime$),a(s.ended$,t.endedEvent$),a(s.looped$,t.loopedEvent$),a(s.error$,t.error$),a(s.isBuffering$,t.isBuffering$),a(s.currentBuffer$,t.currentBuffer$),this.subscription.add(s.durationChange$.subscribe((e=>{t.duration$.next(e===1/0?0:e)}))).add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===ih.READY&&this.videoState.setState(ih.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(ih.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState(ih.PLAYING)}),i)).add(s.error$.subscribe(t.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ao(this.video,e.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(t.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe((i=>{switch(i.to){case ih.STOPPED:t.position$.next(0),t.duration$.next(0),e.playbackState.setState(P.STOPPED);break;case ih.READY:break;case ih.PAUSED:e.playbackState.setState(P.PAUSED);break;case ih.PLAYING:e.playbackState.setState(P.PLAYING);break;default:return o(i.to)}}),i)).add(d(e.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,l(['init'])).pipe(m(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i))}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(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:Dn.INVARIANT}),this.video.srcObject=t,In(this.params.desiredState.playbackState,P.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ih.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(t){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',category:r.EXTERNAL_API,message:t.message,thrown:t})}playIfAllowed(){Oo(this.video).then((t=>{t||(this.videoState.setState(ih.PAUSED),In(this.params.desiredState.playbackState,P.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}}class Th{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 Eh=co(),wh=(null===(sh=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===sh?void 0:sh.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),$h=document.createElement('video'),kh={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(ah=null===(rh=window.SourceBuffer)||void 0===rh?void 0:rh.prototype)||void 0===ah?void 0:ah.appendBuffer)),hls:Boolean((null===(nh=$h.canPlayType)||void 0===nh?void 0:nh.call($h,'application/x-mpegurl'))||(null===(oh=$h.canPlayType)||void 0===oh?void 0:oh.call($h,'vnd.apple.mpegURL'))),webrtc:Boolean(window.RTCPeerConnection)},Ah={mp4:Boolean(null===(dh=$h.canPlayType)||void 0===dh?void 0:dh.call($h,'video/mp4')),webm:Boolean(null===(hh=$h.canPlayType)||void 0===hh?void 0:hh.call($h,'video/webm'))},Ph={h264:Boolean(null===(lh=null===(uh=window.MediaSource)||void 0===uh?void 0:uh.isTypeSupported)||void 0===lh?void 0:lh.call(uh,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(ph=null===(ch=window.MediaSource)||void 0===ch?void 0:ch.isTypeSupported)||void 0===ph?void 0:ph.call(ch,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(fh=null===(mh=window.MediaSource)||void 0===mh?void 0:mh.isTypeSupported)||void 0===fh?void 0:fh.call(mh,'video/webm; codecs="vp9"')),aac:Boolean(null===(gh=null===(vh=window.MediaSource)||void 0===vh?void 0:vh.isTypeSupported)||void 0===gh?void 0:gh.call(vh,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(bh=null===(Sh=window.MediaSource)||void 0===Sh?void 0:Sh.isTypeSupported)||void 0===bh?void 0:bh.call(Sh,'audio/webm; codecs="opus"'))},Rh=(Ph.h264||Ph.h265)&&Ph.aac,Dh=!Eh,_h=kh.hls&&Ah.mp4&&(wh||Eh),Ih=Boolean(window.WebSocket);const Ch=2e4,Lh=3,xh={cacheDuration:12e4},Nh={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Oh={maxPausedTime:3e4},Bh={maxPausedTime:3e4};class Mh{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,n=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new Th(((t,e=!1)=>t.filter((t=>{switch(t){case R.DASH:return kh.mse&&Ah.mp4&&Rh&&Dh;case R.DASH_SEP:return kh.mse&&Ah.mp4&&Rh;case R.DASH_WEBM:return kh.mse&&Ah.webm&&Ph.vp9&&Ph.opus;case R.DASH_LIVE:case R.DASH_ONDEMAND:return kh.mse&&Ah.mp4&&Rh;case R.HLS:case R.HLS_LIVE:case R.HLS_ONDEMAND:return _h||e&&kh.mse&&Ah.mp4&&Rh;case R.MPEG:return Ah.mp4;case R.DASH_LIVE_WEBM:return!1;case R.WEB_RTC_LIVE:return kh.webrtc&&Ih&&Ph.h264&&(Ah.mp4||Ah.webm);default:return o(t)}})))(n.filter((t=>s(r.sources[t]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new Th(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(a(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',category:r.WTF,message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const t=this.current$.getValue().destination;p(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case D.SCREEN:return this.createScreenProvider(e);case D.CHROMECAST:return this.createChromecastProvider(e);default:return o(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r=this.providerOutput,a={container:i,source:null,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case R.DASH:{const i=this.applyFailoverHost(e[t]);return p(i),new ed({...a,source:i,config:xh})}case R.DASH_SEP:case R.DASH_WEBM:case R.DASH_ONDEMAND:{const i=this.applyFailoverHost(e[t]);return p(i),this.params.tuning.useDashJs?new xo({...a,source:i,format:t,config:Bh}):new Ud({...a,source:i})}case R.HLS:case R.HLS_ONDEMAND:{const i=this.applyFailoverHost(e[t]);return p(i),_h||!this.params.tuning.useHlsJs?new Xd({...a,source:i}):new Hd({...a,source:i})}case R.HLS_LIVE:{const i=this.applyFailoverHost(e[t]);return p(i),new Jd({...a,source:i,config:Oh})}case R.MPEG:{const i=this.applyFailoverHost(e[t]);return p(i),new Kd({...a,source:i})}case R.DASH_LIVE:{const i=this.applyFailoverHost(e[t]);return p(i),new Qo({...a,source:i,config:Nh})}case R.WEB_RTC_LIVE:{const a=this.applyFailoverHost(e[t]);return p(a),new yh({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return o(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return p(n),new Vn({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?D.CHROMECAST:D.SCREEN}chooseFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case D.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return o(t)}}skipFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.next();case D.CHROMECAST:return this.chromecastFormatsIterator.next();default:return o(t)}}handleNoFormatsError(t){switch(t){case D.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case D.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return o(t)}}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{...t,url:i(t.url)}}return Rn(Object.entries(t).map((([t,e])=>[t,i(e)])))}initProviderErrorHandling(){const t=new i;let s=!1,a=0;var n;return t.add(d(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ch,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(b((({type:t})=>void 0!==t)))},new T((t=>{const s=new i,r=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),a=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,l='unknown';return s.add(r.subscribe((t=>{h&&window.clearTimeout(h),l=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(a.subscribe((()=>{window.clearTimeout(h),l='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(l)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,category:r.WTF,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),t.add(this.current$.subscribe((()=>{s=!1;const e=this.params.desiredState.playbackState.transitionEnded$.pipe(b((({to:t})=>t===P.PLAYING)),g()).subscribe((()=>s=!0));t.add(e)}))),t.add(this.providerError$.subscribe((t=>{if(this.current$.getValue().destination===D.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>this.switchToNextProvider()),(()=>this.params.dependencies.chromecastInitializer.disconnect()));else{const e=t.category===r.NETWORK,i=this.params.failoverHosts.length>0&&(void 0===this.failoverIndex||this.failoverIndex<this.params.failoverHosts.length-1),n=a<Lh;i&&(e&&s||!n)?(this.failoverIndex=void 0===this.failoverIndex?0:this.failoverIndex+1,this.reinitProvider()):n?(a++,this.reinitProvider()):this.switchToNextProvider()}}))),t}}const Uh=(t,e,i)=>i*e+(1-i)*t;class Vh{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new ko(`raw_${s}`),this.smoothedSeries$=new ko(`smoothed_${s}`),this.reportedSeries$=new ko(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=(this.pastMeasures[t]-this.smoothed)**2,i++);e/=i;const s=Math.sqrt(e),r=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=Uh(this.slow,t,this.params.emaAlphaSlow),this.fast=Uh(this.fast,t,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>r||this.smoothed<n||(a(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 Fh;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Fh||(Fh={}));const qh=new Map;let Hh=Fh.RUNTIME;const Gh=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Gh,'test'),localStorage.removeItem(Gh),Hh=Fh.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Gh),Hh=Fh.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Hh=Fh.RUNTIME}}})();const Yh=(t,e)=>{switch(Hh){case Fh.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Fh.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Fh.RUNTIME:return void qh.set(t,e);default:o(Hh)}},zh=window.navigator.connection,Qh=()=>{const t=null==zh?void 0:zh.downlink;if(s(t)&&10!==t)return 1e3*t},Wh=()=>{const t=null==zh?void 0:zh.rtt;if(s(t)&&3e3!==t)return t},jh=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Jh{constructor(e){var r,a;this.subscription=new i,this.concurrentDownloads=new Set,this.tuningConfig=e;const o=Jh.load('one_video_throughput')||(e.useBrowserEstimation?Qh():void 0)||5e3,d=null!==(a=null!==(r=Jh.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?Wh():void 0)&&void 0!==a?a:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(jh(o,d,e.rttPenaltyRequestSize)),this.throughput=new Vh({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Vh({initial:d,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=Qh();t&&this.throughput.next(t);const e=Wh();s(e)&&this.rtt.next(e)};zh&&'onchange'in zh&&this.subscription.add(n(zh,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Yh('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Yh('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(v({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>jh(t,i,e.rttPenaltyRequestSize))),b((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let e=0,s=y();const r=new i;switch(this.subscription.add(r),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:r.add(n(t,'progress').pipe(g()).subscribe((t=>{e=t.loaded,s=y()})));break;case 1:case 0:r.add(n(t,'loadstart').subscribe((()=>{e=0,s=y()})))}r.add(n(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=y(),a=t-e,n=r-s;this.addRawSpeed(a,n,1)}this.concurrentDownloads.delete(t),r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=y();let r=0,a=y();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:h})=>{d?(this.addRawSpeed(i,y()-s,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,r+=h.byteLength,r>=this.tuningConfig.streamMinSampleSize&&y()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,y()-a,this.concurrentDownloads.size),r=0,a=y()),await(null==e?void 0:e.read().then(o,n)))};this.concurrentDownloads.add(t),null==e||e.read().then(o,n)}addRawSpeed(t,e,i=1){if(Jh.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){var e;const i=(t=>{var e,i;switch(Hh){case Fh.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case Fh.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case Fh.RUNTIME:return qh.get(t);default:o(Hh)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const Xh={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 Kh=({playbackState:t,seekState:e,playbackAbort$:r,looped$:n,position$:o})=>new T((h=>{let l;const c=t.transitionEnded$.pipe(b((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=t.stateChangeEnded$.pipe(b((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=e.stateChangeEnded$.pipe(b((({to:e})=>{var i,s;return e.state===C.Requested&&(null!==(s=null===(i=t.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:t.getState())===P.PLAYING}))),f=e.stateChangeEnded$.pipe(b((({from:e,to:i})=>{var s,r;return e.state===C.Applying&&i.state===C.None&&(null!==(r=null===(s=t.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:t.getState())===P.PLAYING}))),v=d(c,f).pipe(u((()=>o.getValue())),b(s)),g=d(d(p,m,r),n).pipe(u((()=>o.getValue())),b(s));return(new i).add(v.subscribe((t=>{l=t}))).add(g.subscribe((t=>{if(a(l)||l===t)return;const e={from:l,to:t};l=void 0,h.next(e)})))})),Zh={[D.SCREEN]:{vod:[..._h?[R.HLS,R.HLS_ONDEMAND]:[],R.DASH_WEBM,R.DASH_SEP,R.DASH,R.DASH_ONDEMAND,..._h?[]:[R.HLS,R.HLS_ONDEMAND],R.MPEG],live:_h?[R.WEB_RTC_LIVE,R.HLS_LIVE,R.DASH_LIVE]:[R.WEB_RTC_LIVE,R.DASH_LIVE,R.HLS_LIVE]},[D.CHROMECAST]:{vod:[R.DASH_WEBM,R.DASH_SEP,R.DASH_ONDEMAND,R.HLS,R.HLS_ONDEMAND,R.MPEG],live:[R.HLS_LIVE]}};class tu{constructor(s={}){if(this.subscription=new i,this.logger=new k,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Mn(P.STOPPED),seekState:new Mn({state:C.None}),volume:new Mn({volume:1,muted:!1}),videoTrack:new Mn(void 0),autoVideoTrackSwitching:new Mn(!0),autoVideoTrackLimits:new Mn({}),isLooped:new Mn(!1),playbackRate:new Mn(1),externalTextTracks:new Mn([]),currentTextTrack:new Mn(void 0),textTrackCuesSettings:new Mn({})},this.info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentPlaybackRate$:new t(1),currentBuffer$:new t({start:0,end:0}),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(_.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={inited$:new e,started$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,canplay$:new e,log$:new e},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:wo},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Xh)){const s=Xh[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?{...s,...r}:null!=r?r:s}return e})(s),this.chromecastInitializer=new L({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Jh(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),a=`Player.${String(e)}`,n=`Exception calling ${a} (${s.join(', ')})`;throw this.events.fatalError$.next({id:a,category:r.WTF,message:n,thrown:t}),t}}}})}initVideo(t){var e,i,s;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return p(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new Mh({screenFormatsPriority:[...Zh[D.SCREEN].live,...Zh[D.SCREEN].vod],chromecastFormatsPriority:[...Zh[D.CHROMECAST].live,...Zh[D.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},failoverHosts:null!==(s=t.failoverHosts)&&void 0!==s?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t,!1),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){p(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setPlaybackRate(t){var e;p(this.providerContainer);const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(t),i.playbackRate=t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){p(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(a(t))return this.info.position$.getValue();const e=this.desiredState.seekState.getState(),i=e.state===C.None?void 0:e.position;return s(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(d(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((()=>!this.isPlaybackStarted)),b((t=>t.to===P.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=y(),this.events.inited$.next())}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===C.Requested?this.desiredState.seekState.setState({...t,state:C.Applying}):this.events.managedError$.next({id:`WillSeekIn${t.state}`,category:r.WTF,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>Bn(t)?1:Bn(e)?-1:Ln(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(u((t=>t?{start:t.from,end:t.to}:{start:0,end:0}))).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(u((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>d(t.stateChangeEnded$.pipe(u((({to:t})=>{var e;return t.state===C.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),b(s)),e.pipe(b((()=>t.getState().state===C.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(d(e.providerOutput.endedEvent$.pipe(S(!0)),e.providerOutput.seekedEvent$.pipe(S(!1))).pipe(c()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(u((t=>({id:'NoProviders',category:r.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(g(),u((()=>y()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(g(),u((()=>y()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(g(),u((()=>y()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const a=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>a.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>a.next(!0))));const o=new t(!0);this.subscription.add(e.current$.subscribe((()=>o.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(b((({to:t})=>t===P.PLAYING)),g()).subscribe((()=>o.next(!1))));let h=0;const l=d(e.providerOutput.isBuffering$,a,o).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=a.getValue()||o.getValue();return t&&!i})),c());this.subscription.add(l.subscribe((t=>{t?h=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(h),this.info.isStalled$.next(!1))})));const m=new i;this.subscription.add(m);const f=d(n(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(b((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((e=>{switch(p(this.providerContainer),m.unsubscribe(),e){case!0:{const e=new t(void 0);m.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),m.add(Kh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:f,looped$:this.events.looped$,position$:e}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:m.add(Kh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:f,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(u((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(b((t=>t.length>0)),g()).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=Ro(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(d(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;p(this.providerContainer),p(e),Eo={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{To=t})),this.providerContainer.current$.subscribe((({type:t})=>$o('provider',t))),e.duration$.subscribe((t=>$o('duration',t))),e.availableVideoTracks$.pipe(b((t=>!!t.length)),g()).subscribe((t=>$o('tracks',t))),this.events.fatalError$.subscribe(new ko('fatalError')),this.events.managedError$.subscribe(new ko('managedError')),e.position$.subscribe(new ko('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new ko('quality')),this.info.currentBuffer$.subscribe(new ko('buffer')),e.isBuffering$.subscribe(new ko('isBuffering'))].forEach((t=>this.subscription.add(t))),$o('codecs',Object.keys(Ph).filter((t=>Ph[t])))}}const eu='@vkontakte/videoplayer-core@2.0.77';export{_ as ChromecastState,I as HttpConnectionType,P as PlaybackState,tu as Player,eu as SDK_VERSION,R as VideoFormat,Dn as VideoQuality};
6
+ import{ValueSubject as b,Subject as L,Subscription as se,isNonNullable as A,ErrorCategory as x,isNullable as ee,fromEvent as G,assertNever as M,merge as V,tap as Ar,map as w,observableFrom as ke,filterChanged as me,assertNonNullable as P,debounce as Oe,timeout as So,combine as Ke,once as ge,mapTo as yt,filter as q,now as fe,Observable as di,abortable as xe,getExponentialDelay as kr,interval as go,Logger as bo}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Xp,Subject as Zp,Subscription as em,ValueSubject as tm}from"@vkontakte/videoplayer-shared/es2018.esm.js";import yo from"lodash/debounce.js";const To="2.0.78",Eo="@vkontakte/videoplayer-core";var m;(function(s){s.STOPPED="stopped",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Ae;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));var Ee;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ee||(Ee={}));var ni;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(ni||(ni={}));var F;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(F||(F={}));var $o=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class wo{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(Ee.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new b(Ee.NOT_AVAILABLE),this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=A((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||$o("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:x.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 i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){A(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();ee(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();ee(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),i=cast.framework.CastContext.getInstance();this.subscription.add(G(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.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 M(r.sessionState)}})).add(V(G(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ar(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),ke([i.getCastState()])).pipe(me(),w(_o),Ar(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ee.CONNECTED,o=A(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(ee(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ee.CONNECTED?A(this.connection$.getValue())?Ee.CONNECTED:Ee.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:x.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const _o=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ee.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ee.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ee.CONNECTING;case cast.framework.CastState.CONNECTED:return Ee.CONNECTED;default:return M(s)}};var Pr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},et=function(s){try{return!!s()}catch(e){return!0}},Ao=et,Ki=!Ao(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),ja=Ki,za=Function.prototype,Hs=za.call,ko=ja&&za.bind.bind(Hs,Hs),Tt=ja?ko:function(s){return function(){return Hs.apply(s,arguments)}},Wa=Tt,Po=Wa({}.toString),Ro=Wa("".slice),Xs=function(s){return Ro(Po(s),8,-1)},Io=Tt,Do=et,Co=Xs,as=Object,Lo=Io("".split),xo=Do(function(){return!as("z").propertyIsEnumerable(0)})?function(s){return Co(s)=="String"?Lo(s,""):as(s)}:as,Zs=function(s){return s==null},Oo=Zs,No=TypeError,Qa=function(s){if(Oo(s))throw No("Can't call method on "+s);return s},Bo=xo,Mo=Qa,ui=function(s){return Bo(Mo(s))},Uo=function(){},Mt={},bi=function(s){return s&&s.Math==Math&&s},Ye=bi(typeof globalThis=="object"&&globalThis)||bi(typeof window=="object"&&window)||bi(typeof self=="object"&&self)||bi(typeof Pr=="object"&&Pr)||function(){return this}()||Function("return this")(),Gs=typeof document=="object"&&document.all,Fo=typeof Gs=="undefined"&&Gs!==void 0,Ja={all:Gs,IS_HTMLDDA:Fo},Ka=Ja,Vo=Ka.all,Be=Ka.IS_HTMLDDA?function(s){return typeof s=="function"||s===Vo}:function(s){return typeof s=="function"},Ho=Ye,Go=Be,Rr=Ho.WeakMap,qo=Go(Rr)&&/native code/.test(String(Rr)),Ir=Be,Xa=Ja,Yo=Xa.all,Ut=Xa.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Ir(s)||s===Yo}:function(s){return typeof s=="object"?s!==null:Ir(s)},jo=et,ut=!jo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ft={},zo=Ye,Dr=Ut,qs=zo.document,Wo=Dr(qs)&&Dr(qs.createElement),Za=function(s){return Wo?qs.createElement(s):{}},Qo=ut,Jo=et,Ko=Za,en=!Qo&&!Jo(function(){return Object.defineProperty(Ko("div"),"a",{get:function(){return 7}}).a!=7}),Xo=ut,Zo=et,tn=Xo&&Zo(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ed=Ut,td=String,id=TypeError,Vt=function(s){if(ed(s))return s;throw id(td(s)+" is not an object")},sd=Ki,yi=Function.prototype.call,Et=sd?yi.bind(yi):function(){return yi.apply(yi,arguments)},er={},ns=er,os=Ye,rd=Be,Cr=function(s){return rd(s)?s:void 0},tr=function(s,e){return arguments.length<2?Cr(ns[s])||Cr(os[s]):ns[s]&&ns[s][e]||os[s]&&os[s][e]},ad=Tt,sn=ad({}.isPrototypeOf),nd=typeof navigator!="undefined"&&String(navigator.userAgent)||"",rn=Ye,ds=nd,Lr=rn.process,xr=rn.Deno,Or=Lr&&Lr.versions||xr&&xr.version,Nr=Or&&Or.v8,Le,Vi;Nr&&(Le=Nr.split("."),Vi=Le[0]>0&&Le[0]<4?1:+(Le[0]+Le[1]));!Vi&&ds&&(Le=ds.match(/Edge\/(\d+)/),(!Le||Le[1]>=74)&&(Le=ds.match(/Chrome\/(\d+)/),Le&&(Vi=+Le[1])));var od=Vi,Br=od,dd=et,an=!!Object.getOwnPropertySymbols&&!dd(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Br&&Br<41}),ud=an,nn=ud&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ld=tr,cd=Be,hd=sn,fd=nn,pd=Object,on=fd?function(s){return typeof s=="symbol"}:function(s){var e=ld("Symbol");return cd(e)&&hd(e.prototype,pd(s))},md=String,ir=function(s){try{return md(s)}catch(e){return"Object"}},vd=Be,Sd=ir,gd=TypeError,sr=function(s){if(vd(s))return s;throw gd(Sd(s)+" is not a function")},bd=sr,yd=Zs,rr=function(s,e){var t=s[e];return yd(t)?void 0:bd(t)},us=Et,ls=Be,cs=Ut,Td=TypeError,Ed=function(s,e){var t,i;if(e==="string"&&ls(t=s.toString)&&!cs(i=us(t,s))||ls(t=s.valueOf)&&!cs(i=us(t,s))||e!=="string"&&ls(t=s.toString)&&!cs(i=us(t,s)))return i;throw Td("Can't convert object to primitive value")},Hi={},$d={get exports(){return Hi},set exports(s){Hi=s}},wd=!0,Mr=Ye,_d=Object.defineProperty,Ad=function(s,e){try{_d(Mr,s,{value:e,configurable:!0,writable:!0})}catch(t){Mr[s]=e}return e},kd=Ye,Pd=Ad,Ur="__core-js_shared__",Rd=kd[Ur]||Pd(Ur,{}),dn=Rd,Fr=dn;($d.exports=function(s,e){return Fr[s]||(Fr[s]=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 Id=Qa,Dd=Object,ar=function(s){return Dd(Id(s))},Cd=Tt,Ld=ar,xd=Cd({}.hasOwnProperty),lt=Object.hasOwn||function(e,t){return xd(Ld(e),t)},Od=Tt,Nd=0,Bd=Math.random(),Md=Od(1 .toString),un=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Md(++Nd+Bd,36)},Ud=Ye,Fd=Hi,Vr=lt,Vd=un,Hd=an,Gd=nn,It=Ud.Symbol,hs=Fd("wks"),qd=Gd?It.for||It:It&&It.withoutSetter||Vd,tt=function(s){return Vr(hs,s)||(hs[s]=Hd&&Vr(It,s)?It[s]:qd("Symbol."+s)),hs[s]},Yd=Et,Hr=Ut,Gr=on,jd=rr,zd=Ed,Wd=tt,Qd=TypeError,Jd=Wd("toPrimitive"),Kd=function(s,e){if(!Hr(s)||Gr(s))return s;var t=jd(s,Jd),i;if(t){if(e===void 0&&(e="default"),i=Yd(t,s,e),!Hr(i)||Gr(i))return i;throw Qd("Can't convert object to primitive value")}return e===void 0&&(e="number"),zd(s,e)},Xd=Kd,Zd=on,nr=function(s){var e=Xd(s,"string");return Zd(e)?e:e+""},eu=ut,tu=en,iu=tn,Ti=Vt,qr=nr,su=TypeError,fs=Object.defineProperty,ru=Object.getOwnPropertyDescriptor,ps="enumerable",ms="configurable",vs="writable";Ft.f=eu?iu?function(e,t,i){if(Ti(e),t=qr(t),Ti(i),typeof e=="function"&&t==="prototype"&&"value"in i&&vs in i&&!i[vs]){var r=ru(e,t);r&&r[vs]&&(e[t]=i.value,i={configurable:ms in i?i[ms]:r[ms],enumerable:ps in i?i[ps]:r[ps],writable:!1})}return fs(e,t,i)}:fs:function(e,t,i){if(Ti(e),t=qr(t),Ti(i),tu)try{return fs(e,t,i)}catch(r){}if("get"in i||"set"in i)throw su("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Xi=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},au=ut,nu=Ft,ou=Xi,li=au?function(s,e,t){return nu.f(s,e,ou(1,t))}:function(s,e,t){return s[e]=t,s},du=Hi,uu=un,Yr=du("keys"),or=function(s){return Yr[s]||(Yr[s]=uu(s))},dr={},lu=qo,ln=Ye,cu=Ut,hu=li,Ss=lt,gs=dn,fu=or,pu=dr,jr="Object already initialized",Ys=ln.TypeError,mu=ln.WeakMap,Gi,oi,qi,vu=function(s){return qi(s)?oi(s):Gi(s,{})},Su=function(s){return function(e){var t;if(!cu(e)||(t=oi(e)).type!==s)throw Ys("Incompatible receiver, "+s+" required");return t}};if(lu||gs.state){var Ve=gs.state||(gs.state=new mu);Ve.get=Ve.get,Ve.has=Ve.has,Ve.set=Ve.set,Gi=function(s,e){if(Ve.has(s))throw Ys(jr);return e.facade=s,Ve.set(s,e),e},oi=function(s){return Ve.get(s)||{}},qi=function(s){return Ve.has(s)}}else{var kt=fu("state");pu[kt]=!0,Gi=function(s,e){if(Ss(s,kt))throw Ys(jr);return e.facade=s,hu(s,kt,e),e},oi=function(s){return Ss(s,kt)?s[kt]:{}},qi=function(s){return Ss(s,kt)}}var gu={set:Gi,get:oi,has:qi,enforce:vu,getterFor:Su},bu=Ki,cn=Function.prototype,zr=cn.apply,Wr=cn.call,yu=typeof Reflect=="object"&&Reflect.apply||(bu?Wr.bind(zr):function(){return Wr.apply(zr,arguments)}),Tu=Xs,Eu=Tt,hn=function(s){if(Tu(s)==="Function")return Eu(s)},fn={},pn={},mn={}.propertyIsEnumerable,vn=Object.getOwnPropertyDescriptor,$u=vn&&!mn.call({1:2},1);pn.f=$u?function(e){var t=vn(this,e);return!!t&&t.enumerable}:mn;var wu=ut,_u=Et,Au=pn,ku=Xi,Pu=ui,Ru=nr,Iu=lt,Du=en,Qr=Object.getOwnPropertyDescriptor;fn.f=wu?Qr:function(e,t){if(e=Pu(e),t=Ru(t),Du)try{return Qr(e,t)}catch(i){}if(Iu(e,t))return ku(!_u(Au.f,e,t),e[t])};var Cu=et,Lu=Be,xu=/#|\.prototype\./,ci=function(s,e){var t=Nu[Ou(s)];return t==Mu?!0:t==Bu?!1:Lu(e)?Cu(e):!!e},Ou=ci.normalize=function(s){return String(s).replace(xu,".").toLowerCase()},Nu=ci.data={},Bu=ci.NATIVE="N",Mu=ci.POLYFILL="P",Uu=ci,Jr=hn,Fu=sr,Vu=Ki,Hu=Jr(Jr.bind),Sn=function(s,e){return Fu(s),e===void 0?s:Vu?Hu(s,e):function(){return s.apply(e,arguments)}},Ei=Ye,Gu=yu,qu=hn,Yu=Be,ju=fn.f,zu=Uu,Pt=er,Wu=Sn,Rt=li,Kr=lt,Qu=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Gu(s,this,arguments)};return e.prototype=s.prototype,e},ur=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Ei:r?Ei[t]:(Ei[t]||{}).prototype,o=i?Pt:Pt[t]||Rt(Pt,t,{})[t],u=o.prototype,d,l,c,h,f,v,p,S,g;for(h in e)d=zu(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Kr(n,h),v=o[h],l&&(s.dontCallGetSet?(g=ju(n,h),p=g&&g.value):p=n[h]),f=l&&p?p:e[h],!(l&&typeof v==typeof f)&&(s.bind&&l?S=Wu(f,Ei):s.wrap&&l?S=Qu(f):a&&Yu(f)?S=qu(f):S=f,(s.sham||f&&f.sham||v&&v.sham)&&Rt(S,"sham",!0),Rt(o,h,S),a&&(c=t+"Prototype",Kr(Pt,c)||Rt(Pt,c,{}),Rt(Pt[c],h,f),s.real&&u&&(d||!u[h])&&Rt(u,h,f)))},js=ut,Ju=lt,gn=Function.prototype,Ku=js&&Object.getOwnPropertyDescriptor,lr=Ju(gn,"name"),Xu=lr&&function(){}.name==="something",Zu=lr&&(!js||js&&Ku(gn,"name").configurable),el={EXISTS:lr,PROPER:Xu,CONFIGURABLE:Zu},bn={},tl=Math.ceil,il=Math.floor,sl=Math.trunc||function(e){var t=+e;return(t>0?il:tl)(t)},rl=sl,cr=function(s){var e=+s;return e!==e||e===0?0:rl(e)},al=cr,nl=Math.max,ol=Math.min,dl=function(s,e){var t=al(s);return t<0?nl(t+e,0):ol(t,e)},ul=cr,ll=Math.min,cl=function(s){return s>0?ll(ul(s),9007199254740991):0},hl=cl,hr=function(s){return hl(s.length)},fl=ui,pl=dl,ml=hr,Xr=function(s){return function(e,t,i){var r=fl(e),a=ml(r),n=pl(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},vl={includes:Xr(!0),indexOf:Xr(!1)},Sl=Tt,bs=lt,gl=ui,bl=vl.indexOf,yl=dr,Zr=Sl([].push),Tl=function(s,e){var t=gl(s),i=0,r=[],a;for(a in t)!bs(yl,a)&&bs(t,a)&&Zr(r,a);for(;e.length>i;)bs(t,a=e[i++])&&(~bl(r,a)||Zr(r,a));return r},yn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],El=Tl,$l=yn,wl=Object.keys||function(e){return El(e,$l)},_l=ut,Al=tn,kl=Ft,Pl=Vt,Rl=ui,Il=wl;bn.f=_l&&!Al?Object.defineProperties:function(e,t){Pl(e);for(var i=Rl(t),r=Il(t),a=r.length,n=0,o;a>n;)kl.f(e,o=r[n++],i[o]);return e};var Dl=tr,Cl=Dl("document","documentElement"),Ll=Vt,xl=bn,ea=yn,Ol=dr,Nl=Cl,Bl=Za,Ml=or,ta=">",ia="<",zs="prototype",Ws="script",Tn=Ml("IE_PROTO"),ys=function(){},En=function(s){return ia+Ws+ta+s+ia+"/"+Ws+ta},sa=function(s){s.write(En("")),s.close();var e=s.parentWindow.Object;return s=null,e},Ul=function(){var s=Bl("iframe"),e="java"+Ws+":",t;return s.style.display="none",Nl.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(En("document.F=Object")),t.close(),t.F},$i,Ni=function(){try{$i=new ActiveXObject("htmlfile")}catch(e){}Ni=typeof document!="undefined"?document.domain&&$i?sa($i):Ul():sa($i);for(var s=ea.length;s--;)delete Ni[zs][ea[s]];return Ni()};Ol[Tn]=!0;var $n=Object.create||function(e,t){var i;return e!==null?(ys[zs]=Ll(e),i=new ys,ys[zs]=null,i[Tn]=e):i=Ni(),t===void 0?i:xl.f(i,t)},Fl=et,Vl=!Fl(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Hl=lt,Gl=Be,ql=ar,Yl=or,jl=Vl,ra=Yl("IE_PROTO"),Qs=Object,zl=Qs.prototype,wn=jl?Qs.getPrototypeOf:function(s){var e=ql(s);if(Hl(e,ra))return e[ra];var t=e.constructor;return Gl(t)&&e instanceof t?t.prototype:e instanceof Qs?zl:null},Wl=li,_n=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Wl(s,e,t),s},Ql=et,Jl=Be,Kl=Ut,Xl=$n,aa=wn,Zl=_n,ec=tt,Js=ec("iterator"),An=!1,Xe,Ts,Es;[].keys&&(Es=[].keys(),"next"in Es?(Ts=aa(aa(Es)),Ts!==Object.prototype&&(Xe=Ts)):An=!0);var tc=!Kl(Xe)||Ql(function(){var s={};return Xe[Js].call(s)!==s});tc?Xe={}:Xe=Xl(Xe);Jl(Xe[Js])||Zl(Xe,Js,function(){return this});var kn={IteratorPrototype:Xe,BUGGY_SAFARI_ITERATORS:An},ic=tt,sc=ic("toStringTag"),Pn={};Pn[sc]="z";var fr=String(Pn)==="[object z]",rc=fr,ac=Be,Bi=Xs,nc=tt,oc=nc("toStringTag"),dc=Object,uc=Bi(function(){return arguments}())=="Arguments",lc=function(s,e){try{return s[e]}catch(t){}},pr=rc?Bi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=lc(e=dc(s),oc))=="string"?t:uc?Bi(e):(i=Bi(e))=="Object"&&ac(e.callee)?"Arguments":i},cc=fr,hc=pr,fc=cc?{}.toString:function(){return"[object "+hc(this)+"]"},pc=fr,mc=Ft.f,vc=li,Sc=lt,gc=fc,bc=tt,na=bc("toStringTag"),Rn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Sc(r,na)||mc(r,na,{configurable:!0,value:e}),i&&!pc&&vc(r,"toString",gc)}},yc=kn.IteratorPrototype,Tc=$n,Ec=Xi,$c=Rn,wc=Mt,_c=function(){return this},Ac=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Tc(yc,{next:Ec(+!i,t)}),$c(s,r,!1,!0),wc[r]=_c,s},kc=ur,Pc=Et,In=el,Rc=Ac,Ic=wn,Dc=Rn,oa=_n,Cc=tt,da=Mt,Dn=kn,Lc=In.PROPER;In.CONFIGURABLE;Dn.IteratorPrototype;var wi=Dn.BUGGY_SAFARI_ITERATORS,$s=Cc("iterator"),ua="keys",_i="values",la="entries",xc=function(){return this},Oc=function(s,e,t,i,r,a,n){Rc(t,e,i);var o=function(g){if(g===r&&h)return h;if(!wi&&g in l)return l[g];switch(g){case ua:return function(){return new t(this,g)};case _i:return function(){return new t(this,g)};case la:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[$s]||l["@@iterator"]||r&&l[r],h=!wi&&c||o(r),f=e=="Array"&&l.entries||c,v,p,S;if(f&&(v=Ic(f.call(new s)),v!==Object.prototype&&v.next&&(Dc(v,u,!0,!0),da[u]=xc)),Lc&&r==_i&&c&&c.name!==_i&&(d=!0,h=function(){return Pc(c,this)}),r)if(p={values:o(_i),keys:a?h:o(ua),entries:o(la)},n)for(S in p)(wi||d||!(S in l))&&oa(l,S,p[S]);else kc({target:e,proto:!0,forced:wi||d},p);return n&&l[$s]!==h&&oa(l,$s,h,{name:r}),da[e]=h,p},Nc=function(s,e){return{value:s,done:e}},Bc=ui,mr=Uo,ca=Mt,Cn=gu,Mc=Ft.f,Uc=Oc,Ai=Nc,Fc=wd,Vc=ut,Ln="Array Iterator",Hc=Cn.set,Gc=Cn.getterFor(Ln);Uc(Array,"Array",function(s,e){Hc(this,{type:Ln,target:Bc(s),index:0,kind:e})},function(){var s=Gc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Ai(void 0,!0)):t=="keys"?Ai(i,!1):t=="values"?Ai(e[i],!1):Ai([i,e[i]],!1)},"values");var ha=ca.Arguments=ca.Array;mr();mr();mr();if(!Fc&&Vc&&ha.name!=="values")try{Mc(ha,"name",{value:"values"})}catch(s){}var qc=tt,Yc=Mt,jc=qc("iterator"),zc=Array.prototype,Wc=function(s){return s!==void 0&&(Yc.Array===s||zc[jc]===s)},Qc=pr,fa=rr,Jc=Zs,Kc=Mt,Xc=tt,Zc=Xc("iterator"),xn=function(s){if(!Jc(s))return fa(s,Zc)||fa(s,"@@iterator")||Kc[Qc(s)]},eh=Et,th=sr,ih=Vt,sh=ir,rh=xn,ah=TypeError,nh=function(s,e){var t=arguments.length<2?rh(s):e;if(th(t))return ih(eh(t,s));throw ah(sh(s)+" is not iterable")},oh=Et,pa=Vt,dh=rr,uh=function(s,e,t){var i,r;pa(s);try{if(i=dh(s,"return"),!i){if(e==="throw")throw t;return t}i=oh(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pa(i),t},lh=Sn,ch=Et,hh=Vt,fh=ir,ph=Wc,mh=hr,ma=sn,vh=nh,Sh=xn,va=uh,gh=TypeError,Mi=function(s,e){this.stopped=s,this.result=e},Sa=Mi.prototype,bh=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=lh(e,i),d,l,c,h,f,v,p,S=function(T){return d&&va(d,"normal",T),new Mi(!0,T)},g=function(T){return r?(hh(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(a)d=s.iterator;else if(n)d=s;else{if(l=Sh(s),!l)throw gh(fh(s)+" is not iterable");if(ph(l)){for(c=0,h=mh(s);h>c;c++)if(f=g(s[c]),f&&ma(Sa,f))return f;return new Mi(!1)}d=vh(s,l)}for(v=a?s.next:d.next;!(p=ch(v,d)).done;){try{f=g(p.value)}catch(T){va(d,"throw",T)}if(typeof f=="object"&&f&&ma(Sa,f))return f}return new Mi(!1)},yh=nr,Th=Ft,Eh=Xi,$h=function(s,e,t){var i=yh(e);i in s?Th.f(s,i,Eh(0,t)):s[i]=t},wh=ur,_h=bh,Ah=$h;wh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _h(e,function(i,r){Ah(t,i,r)},{AS_ENTRIES:!0}),t}});var kh=er,Ph=kh.Object.fromEntries,Rh={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},Ih=Rh,Dh=Ye,Ch=pr,Lh=li,ga=Mt,xh=tt,ba=xh("toStringTag");for(var ws in Ih){var ya=Dh[ws],_s=ya&&ya.prototype;_s&&Ch(_s)!==ba&&Lh(_s,ba,ws),ga[ws]=ga.Array}var Oh=Ph,Nh=Oh,Bh=Nh,Mh=Bh,hi=Mh,Ct;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ct||(Ct={}));var xt=(s,e=0,t=Ct.OFFSET_P)=>{switch(t){case Ct.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ct.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:M(t)}return s},R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)},oe;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(oe||(oe={}));const Ne={[oe.Q_144P]:{width:256,height:144},[oe.Q_240P]:{width:428,height:240},[oe.Q_360P]:{width:640,height:360},[oe.Q_480P]:{width:856,height:480},[oe.Q_720P]:{width:1280,height:720},[oe.Q_1080P]:{width:1920,height:1080},[oe.Q_1440P]:{width:2560,height:1440},[oe.Q_2160P]:{width:3840,height:2160},[oe.Q_4320P]:{width:7680,height:4320}},Ui=(s,e)=>Ne[s].height>Ne[e].height,Uh=(s,e)=>Ne[s].height>=Ne[e].height,si=(s,e)=>Ne[s].height<Ne[e].height,Fh=(s,e)=>Ne[s].height<=Ne[e].height,Vh=s=>s.sort((e,t)=>e===t?0:e===oe.INVARIANT?1:t===oe.INVARIANT?-1:si(e,t)?1:-1)[0],Hh=Object.keys(Ne).sort((s,e)=>si(s,e)?-1:1),$t=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Hh.find(r=>{const a=Ne[r];return a.width>=i&&a.height>=t})},Gh=s=>Ne[s].height,Yi=s=>s===oe.INVARIANT;class le{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=V(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=V(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=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:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||A(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:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const qh=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.HLS_LIVE:case y.DASH_LIVE:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return M(s)}};var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const Yh=5,jh=5,zh=500,Ta=7e3;class Wh{constructor(e){this.subscription=new se,this.loadMediaTimeoutSubscription=new se,this.videoState=new le(K.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===m.STOPPED){i!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===F.Requested&&i!==K.STOPPED){this.seek(o.position);return}switch(a){case m.PLAYING:{switch(i){case K.PLAYING:break;case K.PAUSED:this.videoState.startTransitionTo(K.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case K.READY:this.videoState.startTransitionTo(K.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case K.STOPPED:this.videoState.startTransitionTo(K.READY),this.prepare();break;default:M(i)}break}case m.PAUSED:{switch(i){case K.PLAYING:this.videoState.startTransitionTo(K.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case K.PAUSED:break;case K.READY:this.videoState.startTransitionTo(K.PAUSED),this.videoState.setState(K.PAUSED);break;case K.STOPPED:this.videoState.startTransitionTo(K.READY),this.prepare();break;default:M(i)}break}default:M(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(qh(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 se;this.subscription.add(e),this.subscription.add(V(this.videoState.stateChangeStarted$.pipe(w(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(w(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new L;e.add(r.pipe(Oe(zh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===F.Applying||Math.abs(o-a)>Yh)&&r.next(o),a=o})),e.add(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<jh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,m.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:M(n)}}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(G(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=V(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0));t(i,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(K.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(K.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:F.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===K.PAUSED||e===K.PLAYING)&&(this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===K.PLAYING||e===K.PAUSED)&&(this.videoState.setState(K.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){const e=this.videoState.getTransition();(e==null?void 0:e.to)===K.READY&&this.videoState.setState(K.READY)}handleRemoteStop(){this.videoState.getState()!==K.STOPPED&&this.videoState.setState(K.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=Vh(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS_LIVE:{const l=i[e];P(l),r=xt(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:x.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return A(u)&&(o.metadata.title=u),A(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===F.Applying||i.state===F.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(So(Ta).subscribe(()=>a(`timeout(${Ta})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===F.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:x.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Ea{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class On extends Ea{constructor(){super(),this.listeners||Ea.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 Nn=class{constructor(){Object.defineProperty(this,"signal",{value:new On,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Nn.prototype[Symbol.toStringTag]="AbortController",On.prototype[Symbol.toStringTag]="AbortSignal");function Bn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Qh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Bn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,v)=>{l.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Zi=Bn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Mn=Zi?Qh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ot=Zi?Mn.fetch:window.fetch;Zi?Mn.Request:window.Request;const gt=Zi?Nn:window.AbortController,Zt=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ri{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=Zt(r.request);if(a>=i.from&&n<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:a})=>a));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(i.url);r&&a&&a.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Zt),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const f=i[h][1];f-r<=2*this.params.minDataSize&&(a=Math.max(a,f))}r===0?a=Math.max(a,r+this.params.minInitSize):a=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 gt,d=u.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(l));const c=h=>{var f,v;throw(v=(f=this.params).onError)===null||v===void 0||v.call(f,{id:"BigRequestParsing",category:x.PARSER,message:"Error parsing response data",thrown:h}),h};return Ot(o,{signal:d}).then(h=>{var f,v,p;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(v=(f=this.params).onDownloadStream)===null||v===void 0||v.call(f,g);const T=S.getReader(),I=parseInt((p=h.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||a-r+1;l.data=new ArrayBuffer(I);const $=new Uint8Array(l.data),_=async({done:C,value:j})=>{C?this.onBigRequestProgress(l):j&&($.set(j,l.loaded),l.loaded+=j.byteLength,this.onBigRequestProgress(l),await(T==null?void 0:T.read().then(_,ri.suppressStreamErrors).catch(c)))};T==null||T.read().then(_,ri.suppressStreamErrors).catch(c)},ri.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:a,response:n}){var o,u,d,l,c,h,f,v;if(!this.activeRequests.has(e)||!a)return;const p=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of p){const{request:g}=S,[T,I]=Zt(g),$=T>=t&&I<=t+r,_=t>=T&&t+r<I,C=a.slice(T-t,Math.min(I-t+1,r));if(($||_)&&(g.requestStartDate=(u=g.requestStartDate)!==null&&u!==void 0?u:new Date,g.firstByteDate=(d=g.firstByteDate)!==null&&d!==void 0?d:new Date,g.bytesLoaded=C.byteLength,g.bytesTotal=i-t),$){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(U=>U!==S)),(c=S.success)===null||c===void 0||c.call(S,C,"",e);const j=n?Array.from(n.headers.entries()).map(([U,N])=>`${U}: ${N}`).join(`\r
7
+ `):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,j,[])}else _&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:x.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of d){const[c,h]=Zt(l.request);(c>=t&&c<i||h>t&&h<=i)&&((u=l==null?void 0:l.error)===null||u===void 0||u.call(l,l.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,a;if(!this.activeRequests.has(e))return;const n=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const o of n){const[u,d]=Zt(o.request);(u>=t&&u<i||d>t&&d<=i)&&((a=o==null?void 0:o.abort)===null||a===void 0||a.call(o,o.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class ji{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(ji.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;ji.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Jh=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new ji(r,e,i)}}),Kh=(s,e)=>{const t=new ri(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return Jh(n,t)}}},!0),()=>t.destroy()};var Xh=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Zh=s=>{const e=new b(1/0),t=new L,i=new b(void 0),r=new b(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,v,p;const S=hi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),$=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),_=(f=$!=null?$:I*1e3)!==null&&f!==void 0?f:NaN;A(_)&&!isNaN(_)&&e.next(_)}const g=(v=S["x-delivery-type"])!==null&&v!==void 0?v:ni.HTTP1,T=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;i.next(g),r.next(T)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,v=h.progress;h.onload=function(...p){return u(this),f(...p)},h.progress=function(...p){return d(this),v(...p)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Nt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},ef=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Nt}),!0),tf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const qe=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=ee(r),d=new se;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},wt=(s,e,t)=>qe(e,()=>s.loop,i=>{A(i)&&(s.loop=i)},{onError:t}),it=(s,e,t,i)=>qe(e,()=>({muted:s.muted,volume:s.volume}),r=>{A(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ct=(s,e,t,i)=>qe(e,()=>s.playbackRate,r=>{A(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),sf=s=>["__",s.language,s.label].join("|"),rf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class je{constructor(){this.available$=new L,this.current$=new b(void 0),this.error$=new L,this.subscription=new se,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:x.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(qe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{A(a)&&this.setExternal(a)},{equal:(a,n)=>A(a)&&A(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(qe(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(G(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(V(G(e,"addtrack"),G(e,"removetrack"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),me((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(V(G(e,"change"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),me()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(G(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(G(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;A(t.align)&&(r.align=t.align),A(t.position)&&(r.position=t.position),A(t.size)&&(r.size=t.size),A(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(je.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:sf(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}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(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))A(e)&&rf(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){P(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){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var st=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class vr{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 Un=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const Ks=3;class af{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Ks&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ks))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Fn=(s,e,t=Ks)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const rt=s=>{const e=f=>G(s,f).pipe(yt(void 0)),i=V(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(f=>G(s,f))).pipe(w(f=>f.type==="ended"?s.readyState<2:s.readyState<3),me()),r=V(G(s,"progress"),G(s,"timeupdate")).pipe(w(()=>Fn(s.buffered,s.currentTime))),a=Un()?Ke({play:e("play").pipe(ge()),playing:e("playing")}).pipe(yt(void 0)):e("playing"),n=G(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),o=G(s,"ratechange").pipe(w(()=>s.playbackRate)),u=G(s,"error").pipe(q(()=>Boolean(s.error||s.played.length)),w(()=>{var f;const v=s.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:x.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(f=s.error)!==null&&f!==void 0?f:void 0}})),d=G(s,"timeupdate").pipe(w(()=>s.currentTime)),l=new L,c=.3;let h;return d.subscribe(f=>{s.loop&&A(h)&&A(f)&&h>=s.duration-c&&f<=c&&l.next(h),h=f}),{playing$:a,pause$:e("pause").pipe(q(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:G(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o}},Sr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var nf=ur,of=ar,df=hr,uf=cr;nf({target:"Array",proto:!0},{at:function(e){var t=of(this),i=df(t),r=uf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var lf=tr,cf=lf,hf=cf,ff=hf("Array","at"),pf=ff,mf=pf,vf=mf,Sf=vf,We=Sf;let gr=!1,Qe={};const gf=s=>{gr=s},bf=()=>{Qe={}},yf=s=>{s(Qe)},ki=(s,e)=>{var t;gr&&(Qe.meta=(t=Qe.meta)!==null&&t!==void 0?t:{},Qe.meta[s]=e)};class Ge{constructor(e){this.name=e}next(e){var t,i;if(!gr)return;Qe.series=(t=Qe.series)!==null&&t!==void 0?t:{};const r=(i=Qe.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Qe.series[this.name]=r}}const Tf=new Ge("best_bitrate"),Ef=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class $f{constructor(){this.history={}}recordSelection(e){this.history[e.id]=fe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const fi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,f;const v=i.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},S=p&&$t(p),g=i.considerPlaybackRate&&A(o)?o:1,T=s.filter(B=>!Yi(B.quality)).sort((B,O)=>Ui(B.quality,O.quality)?-1:1),I=(c=We(T,-1))===null||c===void 0?void 0:c.quality,$=(h=We(T,0))===null||h===void 0?void 0:h.quality,_=ee(r)||A(r.min)&&A(r.max)&&si(r.max,r.min)||A(r.min)&&$&&Ui(r.min,$)||A(r.max)&&I&&si(r.max,I),C=g*Ef(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),U=T.filter(B=>{const O=S?si(B.quality,S):!0,z=A(t)&&isFinite(t)&&A(B.bitrate)?t-a>=B.bitrate*C:!0,J=i.lazyQualitySwitch&&A(i.minBufferToSwitchUp)&&u&&!Yi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Ui(B.quality,u.quality),re=_||(ee(r.max)||Fh(B.quality,r.max))&&(ee(r.min)||Uh(B.quality,r.min));return O&&z&&!J&&re})[0];U&&U.bitrate&&Tf.next(U.bitrate);const N=(f=U!=null?U:T[Math.ceil((T.length-1)/2)])!==null&&f!==void 0?f:s[0],Q=N&&d&&d.history[N.id]&&fe()-d.history[N.id]<=i.trackCooldown&&(!d.last||N.id!==d.last.id);if(N!=null&&N.id&&d&&!Q&&d.recordSelection(N),Q&&(d!=null&&d.last)){const B=d.last;return d==null||d.recordSwitch(B),B}return d==null||d.recordSwitch(N),N};var we=s=>new URL(s).hostname;const wf=300,zi=(s,e=wf)=>new di(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(yo(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),A(u)&&A(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()}),_f=5e3,ei={};var X;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const Se=(s,e)=>new di(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Af{constructor(e){this.subscription=new se,this.videoState=new le(X.DOWNLOADING_LIB),this.textTracksManager=new je,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new b(void 0),this.maxSeekBackTime$=new b(1/0),this.availableFrom$=new b(void 0),this.elementSize$=new b(void 0),this.liveOffset=new vr,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===X.DOWNLOADING_LIB||t===X.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===F.Requested&&t!==X.STOPPED&&i!==m.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case m.STOPPED:{switch(t){case X.STOPPED:break;case X.PLAYING:case X.PAUSED:case X.READY:this.stop();break;default:M(t)}break}case m.PLAYING:{switch(t){case X.PLAYING:break;case X.PAUSED:n&&(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 X.READY:this.play();break;case X.STOPPED:this.prepare();break;default:M(t)}break}case m.PAUSED:{switch(t){case X.PLAYING:this.pause(),this.liveOffset.pause();break;case X.PAUSED:break;case X.READY:this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED);break;case X.STOPPED:this.prepare();break;default:M(t)}break}default:M(i)}},this.video=st(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:x.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),_f);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ei.MediaPlayer=r.MediaPlayer,ei.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ei.MediaPlayer,"dashjs not loaded"),P(ei.Debug,"dashjs not loaded"),this.player=ei.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?Sr(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Kh(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&&tf(this.player),Xh(this.player),this.params.tuning.requestQuick&&ef(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=p=>{e.error$.next({id:"DashIFProvider",category:x.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,S)=>this.subscription.add(p.subscribe(S,i));r(zi(this.video),this.elementSize$),r(Se(this.player,"error").pipe(w(p=>{const S=typeof p.error=="object"?p.error.code:p.error,g=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(Se(this.player,"playbackError").pipe(w(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(q(({mediaType:p})=>p==="video"),w(({newQuality:p})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===p))===null||S===void 0?void 0:S.track}));a.pipe(q(A)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(q(({to:p})=>p===X.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(qe(t.videoTrack,()=>{var p,S;const g=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===g))===null||p===void 0?void 0:p.track)===null||S===void 0?void 0:S.id},p=>{var S;if(ee(p))return;const g=(S=this.videoTracks.find(({track:T})=>T.id===p))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe(w(p=>p==null?void 0:p.id)),onError:i}))},i)),this.subscription.add(qe(t.autoVideoTrackSwitching,()=>{var p,S,g;return(g=(S=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(q(({mediaType:p})=>p==="video"),w(({state:p})=>p==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:S}})=>{var g,T;const I=this.player.getDashMetrics(),$=I.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),_=(g=I.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&g!==void 0?g:ni.HTTP1,C=(T={1:!0,0:!1}[$])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(_),this.params.output.httpConnectionReused$.next(C),e.hostname$.next(we(S))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(p),this.videoTracks=[];const T=this.player.getQualityFor("video");let I;for(const $ of this.player.getBitrateInfoListFor("video")){const _=$.qualityIndex.toString(10),C=$t($),j=$.bitrate/1e3,U={width:$.width,height:$.height},N=this.frameRatesByFrameHeight[$.height];if(C){const Q={id:_,quality:C,bitrate:j,size:U,fps:N};this.videoTracks.push({track:Q,bitrateInfo:$}),$.qualityIndex===T&&(I=Q)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:$})=>$)),I&&e.currentVideoTrack$.next(I),this.videoState.setState(X.STREAM_INITIALIZED),this.videoState.startTransitionTo(X.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const S=p.requestEndDate.getTime()-p.firstByteDate.getTime(),g=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(V(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=fi(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:T})=>T===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(Ke({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(q(A))}).pipe(q(({isLive:p})=>p),w(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe(w(({time:p})=>p!=null?p:0));r(Ke({availableFrom:this.availableFrom$.pipe(q(A)),currentTime:n}),({availableFrom:p,currentTime:S})=>this.params.output.liveTime$.next(p+S*1e3)),r(n.pipe(q(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe(w(()=>Fn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(X.PLAYING),R(t.playbackState,m.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(X.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(X.PAUSED),R(t.playbackState,m.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===X.READY&&this.videoState.setState(X.READY)}),r(this.isLive$,e.isLive$),r(zi(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Zh(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ke({isLive:this.isLive$,isShort:e.duration$.pipe(w(p=>p<60))}),({isLive:p,isShort:S})=>{const g=!p&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(q(p=>p>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(ge(),yt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(wt(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:v}=rt(this.video);this.subscription.add(it(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(ct(this.video,t.playbackRate,v,i))}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(X.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(X.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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=xt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ct.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(X.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(X.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(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var pi=s=>{switch(s){case"mobile":return oe.Q_144P;case"lowest":return oe.Q_240P;case"low":return oe.Q_360P;case"sd":case"medium":return oe.Q_480P;case"hd":case"high":return oe.Q_720P;case"fullhd":case"full":return oe.Q_1080P;case"quadhd":case"quad":return oe.Q_1440P;case"ultrahd":case"ultra":return oe.Q_2160P}},ht=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function Te(){return fe()}function Vn(s){return Te()-s}function $a(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function kf(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Fi(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",v=7e3,p=2e3,S=()=>{if(u)return;P(l);const O=Vn(l);let z;if(O<p){z=p-O,setTimeout(S,z);return}p*=2,p>v&&(p=v),n&&n.abort(),n=new r,C()};const g=O=>(a=O,B),T=O=>(c=O,B),I=()=>(f="json",B),$=()=>{if(!u){if(--d>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},_=O=>(h=O,B),C=()=>{l=Te(),n=new r,n.open("get",s);let O=0,z,J=0;const re=()=>(P(l),Math.max(l,Math.max(z||0,J||0)));if(a&&n.addEventListener("progress",k=>{const H=Te();a.updateChunk&&k.loaded>O&&(a.updateChunk(re(),k.loaded-O),O=k.loaded,z=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(u)return;P(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const H=n.response.byteLength-O;H&&a.updateChunk&&a.updateChunk(re(),H)}c&&c(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(J=Te(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=f,n.send(),B},B={withBitrateReporting:g,withParallel:_,withJSONResponse:I,withRetryCount:O=>(d=O,B),withRetryInterval:(O,z)=>(A(O)&&(p=O),A(z)&&(v=z),B),withTimeout:O=>(o=O,B),withFinally:T,send:C,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return B}const Pf=100,Rf=2e3,If=500;let Df=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,i){return{start:e,end:t,bytes:i}}_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-If;if(t-e>Rf){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){const a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Pf&&(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 Cf{constructor(e,t,i,r,a){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=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}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 i=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Fi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_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=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}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 Pi=1e4,Ri=3,Lf=300,xf=2e3,Of=6e4,Nf=10,Bf=1,Mf=500;class Uf{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 Df(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=$a(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=$a(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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||A(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{kf(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Cf(Ri,Pi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const $=a&&(!l||l===this.rep);return $||t("Not running!"),$},h=($,_,C)=>{u&&u.abort(),u=Fi(this.urlResolver.resolve($,!1),_,C,()=>this._retryCallback()).withTimeout(Pi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ri).withFinally(()=>{u=null}).send()},f=($,_,C)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),_,C,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=$=>{const _=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${_}=>${$}`),i.playbackRate=$)},p=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),S()},S=()=>{if(!this.lowLatency)v(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const C=Te()-6e4;let j=0;for(let N=0;N<this.bufferStates.length;N++){const Q=this.bufferStates[N];$=Math.min($,Q.buf),Q.ts<C&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${$} drop=${j} jitter=${this.sourceJitter}`);let U=$-Bf;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?v(1.15):U>1?v(1.1):U>.3?v(1.01):v(1)}},g=$=>{let _;const C=()=>_&&_.start?_.start.length:0,j=k=>_.start[k]/1e3,U=k=>_.dur[k]/1e3,N=k=>_.fragIndex+k,Q=(k,H)=>({chunkIdx:N(k),startTS:j(k),dur:U(k),discontinuity:H}),B=()=>{let k=0;if(_&&_.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,de=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,pe=H;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let ve=_.dur.length-1;for(;ve>=0&&(pe-=_.dur[ve],!(pe<=0));--ve);k=Math.min(ve,_.dur.length-1-de),k=Math.max(k,0)}return Q(k,!0)},O=k=>{const H=C();if(!(H<=0)){if(A(k)){for(let de=0;de<H;de++)if(j(de)>k)return Q(de)}return B()}},z=k=>{const H=C(),de=k?k.chunkIdx+1:0,pe=de-_.fragIndex;if(!(H<=0)){if(!k||pe<0||pe-H>Nf)return t(`Resync: offset=${pe} bChunks=${H} chunk=`+JSON.stringify(k)),B();if(!(pe>=H))return Q(de-_.fragIndex,!1)}},J=(k,H,de)=>{d&&d.abort(),d=Fi(this.urlResolver.resolve(k,!0,this.lowLatency),H,de,()=>this._retryCallback()).withTimeout(Pi).withRetryCount(Ri).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,H)=>{J($,de=>{if(!c())return;_=de;const pe=Boolean(_.lowLatency);pe!==this.lowLatency&&p(pe);let ve=0;for(let _e=0;_e<_.dur.length;++_e)ve+=_.dur[_e];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/_.dur.length)),r({name:"index",zeroTime:_.zeroTime,shiftDuration:_.shiftDuration}),this.sourceJitter=_.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,_.jitter/1e3)):1,k(O(H))},()=>this._handleNetworkError())},nextChunk:z}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:$=>{const{videoElement:_,logger:C}=this.params;let j=g(e.jidxUrl),U,N,Q,B,O=0,z,J,re;const k=()=>{z&&(clearTimeout(z),z=void 0);const Z=Math.max(Mf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=O+Z,$e=Te(),Pe=Math.min(1e4,be-$e);O=$e;const ft=()=>{d||c()&&j.seek(()=>{c()&&(O=Te(),H(),k())})};Pe>0?z=window.setTimeout(()=>{this.paused?k():ft()},Pe):ft()},H=()=>{let Z;for(;Z=j.nextChunk(B);)B=Z,Me(Z);const be=j.nextChunk(Q);if(be){if(Q&&be.discontinuity){C("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}_e(be)}else k()},de=(Z,be)=>{if(!c()||!this.sourceBuffer)return;let $e,Pe,ft;const Ue=at=>{window.setTimeout(()=>{c()&&de(Z,be)},at)};if(this.sourceBuffer.updating)C("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const at=Te(),pt=_.currentTime;!this.paused&&_.buffered.length>1&&J===pt&&at-re>500&&(C("Stall suspected; trying to fix"),this._fixupStall()),J!==pt&&(J=pt,re=at);const Gt=this._getBufferSizeSec();if(Gt>30)C(`Buffered ${Gt} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:at,buf:Gt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(_t){if(_t.name==="QuotaExceededError")C("QuotaExceededError; delaying appendBuffer"),ft=this.sourceBuffer.buffered.length,ft!==0&&($e=this.sourceBuffer.buffered.start(0),Pe=pt,Pe-$e>4&&this.sourceBuffer.remove($e,Pe-3)),Ue(1e3);else throw _t}}},pe=()=>{N&&U&&(C([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(Q)]),de(N,function(){N=null,H()}))},ve=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),_e=Z=>{c()&&f(ve(Z),(be,$e)=>{if(c()){if($e/=1e3,N=be,Q=Z,n=Z.startTS,$e){const Pe=Math.min(10,Z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}pe()}},()=>this._handleNetworkError())},Me=Z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(Z),!1)))},Ht=Z=>{c()&&(e.cachedHeader=Z,de(Z,()=>{U=!0,pe()}))};a=!0,j.seek(Z=>{if(c()){if(O=Te(),!Z){k();return}B=Z,!ee($)||Z.startTS>$?_e(Z):(Q=Z,H())}},$),e.cachedHeader?Ht(e.cachedHeader):h(e.headerUrl,Ht,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),A(r)&&(r+=.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,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return A(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=Te();if(this.chunkRateEstimator.addInterval(h,v,f)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:S}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Vn(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=Te();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Fi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Pi).withRetryCount(Ri).withRetryInterval(Lf,xf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ht(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},Of))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var Y;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const Ff=[Y.PAUSED,Y.PLAYING,Y.READY],Vf=[Y.PAUSED,Y.PLAYING,Y.READY];class Hf{constructor(e){this.subscription=new se,this.videoState=new le(Y.STOPPED),this.representations$=new b([]),this.textTracksManager=new je,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new vr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:x.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=pi(c.name))!==null&&n!==void 0?n:$t(c.video),v=c.bitrate/1e3,p={...c.video};if(!f)continue;const S={id:h,quality:f,bitrate:v,size:p};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.MANIFEST_READY&&this.videoState.setState(Y.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),A(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===m.STOPPED){a!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(Y.STOPPED));return}if(!n){if(Vf.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;A(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==m.PAUSED&&d.state===F.Requested&&Ff.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case Y.STOPPED:this.videoState.startTransitionTo(Y.MANIFEST_READY),this.dash.attachSource(xt(this.params.source.url));return;case Y.MANIFEST_READY:this.videoState.startTransitionTo(Y.READY),this.prepare();break;case Y.READY:o===m.PAUSED?this.videoState.setState(Y.PAUSED):o===m.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(Y.PAUSED)}));return;case Y.PLAYING:o===m.PAUSED&&(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case Y.PAUSED:o===m.PLAYING&&(this.videoState.startTransitionTo(Y.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(Y.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return M(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:x.WTF,message:"DashLiveProvider internal logic error",thrown:r})};V(this.videoState.stateChangeStarted$.pipe(w(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=st(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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=rt(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===Y.READY&&this.videoState.setState(Y.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===F.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Y.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ke({zeroTime:this.zeroTime$.pipe(q(A)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(wt(this.video,this.params.desiredState.isLooped,t)).add(it(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ct(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&Gh(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case Y.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(m.STOPPED);break;case Y.MANIFEST_READY:case Y.READY:break;case Y.PAUSED:this.params.desiredState.playbackState.setState(m.PAUSED);break;case Y.PLAYING:this.params.desiredState.playbackState.setState(m.PLAYING);break;default:return M(r.to)}},t)).add(V(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(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 Uf({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,i,r,a,n;const o=this.representations$.getValue(),u=(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(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&A(u)?u:(a=fi(o.map(({track:h})=>h),{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||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.dash.reinit(xt(this.params.source.url,i))}}var Hn=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?ni.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Lt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Gf=s=>{const e=document.createElement("a");return e.href=s,e.origin},qf=s=>{const e=document.createElement("a");return e.href=s,e.host};class Gn{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,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,i,r,a,n,o,u,d;if(P(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=hi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(qf(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!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 Wi{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(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=p=>{r(Wi._str2ua(p.substr(u))),u=p.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=Nt(v)),this._lastXhr=new Gn(v,e.failoverHosts,p=>{this._lastXhr=void 0,f(p);const S=Date.now()-d;this._params.onBandwidthChange({size:p.length,duration:S,speed:8*p.length/(S/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),a==null||a()},p=>{if(p.length-u>o&&f(p),c===0){c=Date.now();return}h=p.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=p.length,c=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},n,(p,S,g)=>this._params.onError(p,S,g))})}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(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};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=Wi._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 i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);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 Yf{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)?)?$/,i=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Nt(i)),new Gn(i,t,r=>{this.attachManifest(r,t,Gf(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,v,p,S,g,T,I,$,_,C,j,U,N,Q,B,O;const z=d.getElementsByTagName("SegmentBase")[0],J=z&&n(z,"indexRange").split("-"),re=z&&z.getElementsByTagName("Initialization")[0],k=re&&n(re,"range").split("-");if(!k||!J){const Me=d.parentElement;if((Me==null?void 0:Me.getAttribute("contentType"))==="text"){const Ht=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(i?i+"/":"")+((v=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||v===void 0?void 0:v.data),be=(p=Me.getAttribute("lang"))!==null&&p!==void 0?p:void 0;Z&&u.push({id:Ht,url:Z,language:be})}return}const H=.1,de=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),pe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const _e=(T=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&T!==void 0?T:void 0;ve=_e?Sr(_e):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number(($=d.attributes.getNamedItem("height"))===null||$===void 0?void 0:$.value),bandwidth:de,baseURL:pe,failoverHosts:t,indexFrom:Number(J[0]),indexTo:Number(J[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(C=(_=d.attributes.getNamedItem("codecs"))===null||_===void 0?void 0:_.value)!==null&&C!==void 0?C:void 0,mimeType:(U=(j=d.attributes.getNamedItem("mimeType"))===null||j===void 0?void 0:j.value)!==null&&U!==void 0?U:void 0,fps:ve,bufferSize:H*de/8,bufferLength:H,name:(Q=(N=d.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.value)!==null&&Q!==void 0?Q:void 0,id:(O=(B=d.attributes.getNamedItem("id"))===null||B===void 0?void 0:B.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.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 i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:f-1}),d=f,u=v}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},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 i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(f);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Wi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.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||ee(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));const jf=[W.PAUSED,W.PLAYING];class zf{constructor(e){this.videoState=new le(W.STOPPED),this.subscription=new se,this.representations$=new b([]),this.currentRepresentation$=new b(void 0),this.textTracksManager=new je,this.elementSize$=new b(void 0),this.dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L},this.handleManifestReady=t=>{var i,r,a;const n=[];for(const o of t){const u=(r=(i=o.name)!==null&&i!==void 0?i:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&pi(o.name))!==null&&a!==void 0?a:$t(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:f,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(W.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=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: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===m.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==m.PAUSED&&n.state===F.Requested&&jf.includes(t)&&this.seek(n.position,n.forcePrecise),t){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:r===m.PAUSED?(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case W.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return M(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),V(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=st(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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new af(this.video),this.dash=new Yf({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,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:x.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,i=o=>{e.error$.next({id:"DashProvider",category:x.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=rt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),this.subscription.add(a.seeking$.subscribe(()=>{ee(this.params.desiredState.seekState.getState().state!==F.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(it(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ct(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(zi(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:x.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(V(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$,G(this.video,"progress")).pipe(w(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&A(f))g=f;else{const T=Lt(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,$=Math.min(T/I,1);g=(u=fi(c.map(({track:_})=>_),{container:p,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:$,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:_})=>_===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return A(g)?(d=c.find(({track:T})=>T.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,i)).add(Ke({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(q(o=>o.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(q(A))}).pipe(ge()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(q(A),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Lt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(we(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=Hn(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),yt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(q(A)).subscribe(this.handleRepresentationPlay,i)).add(V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const 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 M(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}}var Ie;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ie||(Ie={}));var Qi;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Qi||(Qi={}));var De;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(De||(De={}));var te;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(te||(te={}));var Bt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Bt||(Bt={}));var wa=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Wf=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Qf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",_a=Qf?Wf:window.requestIdleCallback;var As,ks;let qn=!1;try{qn=Un()&&parseInt((ks=(As=navigator.userAgent.match(/Version\/(\d+)/))===null||As===void 0?void 0:As[1])!==null&&ks!==void 0?ks:"",10)<16}catch(s){console.error(s)}class Jf{constructor(e){this.bufferFull$=new L,this.error$=new L,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:x.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;qn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!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 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:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category:x.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:M(t)}}}var Aa=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const Yn=new TextDecoder("ascii"),jn=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=Yn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,s.byteLength)-e,n=new DataView(s.buffer,s.byteOffset+e,a);return{id:r,size:t,contents:n}},Kf=s=>Yn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Xf=s=>{const e=jn(s),t=[];let i=0;const r=()=>{const f=e.contents.getUint32(i);return i+=4,f};if((r()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");r();const o=r(),u=r(),d=r(),l=r()&4294967295;let c=u/o*1e3,h=s.byteOffset+s.byteLength+d;for(let f=0;f<l;f++){const v=r(),p=v>>>31,S=v<<1>>>1,g=r();if(r(),p!==0)throw new Error("Unsupported multilevel sidx");const T=g/o*1e3;t.push({status:te.NONE,time:{from:c,to:c+T},byte:{from:h,to:h+S-1}}),c+=T,h+=S}return t},Zf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const r=new DataView(s.buffer,s.byteOffset+e);try{const a=jn(r);if(i||(i=a.id==="mdat"),e+a.size<=s.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},ep={validateData:Kf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Xf,parseFeedableSegmentChunk:Zf};var E;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(D||(D={}));const ka={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},zn=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ji(s,t),r=i in ka,a=r?ka[i].type:D.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=((n&255>>o)<<(o-1)*8)+Ji(u),l=t+o;let c;return l+d>s.byteLength?c=new DataView(s.buffer,s.byteOffset+l):c=new DataView(s.buffer,s.byteOffset+l,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+d,value:c,valueSize:d}},Ji=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint16(0)<<8|s.getUint8(2);case 4:return s.getUint32(0);case 5:return s.getUint32(0)<<8|s.getUint8(4);case 6:return s.getUint32(0)<<16|s.getUint16(4);case 7:return s.getUint32(0)<<32|s.getUint16(4)<<8|s.getUint8(6);case 8:return s.getUint32(0)<<32|s.getUint32(4)}return 0},Je=(s,e)=>{switch(e){case D.SignedInteger:return s.getInt8(0);case D.UnsignedInteger:return Ji(s);case D.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(s);case D.UTF8:return new TextDecoder("utf-8").decode(s);case D.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case D.Master:return s;case D.Binary:return s;default:M(e)}},mi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=zn(i);if(!e(r))return;r.type===D.Master&&mi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},tp=s=>{if(s.getUint32(0)!==E.EBML)return!1;let e,t,i;const r=zn(s);return mi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=Je(o,n):a===E.DocType?t=Je(o,n):a===E.DocTypeReadVersion&&(i=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Wn=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],ip=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],sp=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d;return mi(s,({tag:l,type:c,value:h,valueSize:f})=>{if(l===E.SeekID){const v=Je(h,c);d=Ji(v)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?i=Je(h,c):l===E.Duration?r=Je(h,c):l===E.SeekPosition&&d===E.Cues?u=Je(h,c):a&&n&&Wn.includes(l)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u}},rp=s=>{if(ee(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ap=(s,e)=>{let t=!1,i=!1;const r=o=>A(o.time)&&A(o.position),a=[];let n;return mi(s,({tag:o,type:u,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&r(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=Je(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=Je(d,u));break;default:t&&Wn.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},np=s=>{let e=0,t=!1;try{mi(s,i=>i.tag===E.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ip.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},op={validateData:tp,parseInit:sp,getIndexRange:rp,parseSegments:ap,parseFeedableSegmentChunk:np};class Pa{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.error$=new L,this.gaps=[],this.subscription=new se,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new gt,this.destroyAbortController=new gt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=xe(this.destroyAbortController.signal,async function*(d){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new Jf(this.sourceBuffer),this.subscription.add(G(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),v=>this.error$.next({id:"SegmentEjection",category:x.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(G(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,Aa(this.sourceBuffer.buffered));this.bufferLimit=p,this.pruneBuffer(v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(l,"high",!0);const c=this.initData.get(l.id),h=this.segments.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let f=0;for(const v of h)v.time.from-f>0&&this.gaps.push({representation:l.id,from:f,to:v.time.from}),f=v.time.to;A(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=xe(this.destroyAbortController.signal,async function*(d){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return;this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(ee(c)?yield this.loadInit(l,"high",!1):c instanceof Promise&&(yield c),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal);const h=this.getCurrentPosition();A(h)&&this.maintain(h)}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case Bt.MP4:this.containerParser=ep;break;case Bt.WEBM:this.containerParser=op;break;default:M(i)}this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.representations=new Map(r.map(d=>[d.id,d])),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 gt,this.abortBuffer()}maintain(e){if(ee(this.downloadingRepresentationId)||ee(this.playingRepresentationId)||ee(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Lt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Aa(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),r&&r.status!==te.NONE))return;let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=We(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&Lt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=We(i,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r: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,i){const r=e.findIndex(({status:u,time:{from:d,to:l}})=>u===te.NONE&&(d>i||d<=i&&l>=i)&&l<=i+this.forwardBufferTarget);if(r===-1)return[];if(t!==De.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0;const o=[];for(let u=r;u<a.length&&n<=this.tuning.dash.segmentRequestSize;u++){const d=a[u];if(n+=d.byte.to+1-d.byte.from,d.status===te.NONE||d.status===te.PARTIALLY_EJECTED)o.push(d);else break}return o}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case De.BYTE_RANGE:{r=t.segmentReference.url,a={from:We(e,0).byte.from,to:We(e,-1).byte.to};break}case De.TEMPLATE:{const d=We(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:M(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await xe(u,async function*(){const d=kr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:x.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&A(r)&&(i=Lt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:x.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=c=>{this.abortSegment(c.segment)},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),c.segment.status=te.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const v of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])v.status===te.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=te.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===De.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n(c);continue}const S=f?h.byte.from-i:0,g=f?h.byte.to-i:e.byteLength,T=S<r,I=g<=r;if(h.status===te.DOWNLOADING&&T&&I){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const $=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append($,a).then(_=>_&&!a.aborted?o(c):n(c))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(v,r-S),c.loadedBytes>c.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),_=c.loadedBytes===v?$:this.containerParser.parseFeedableSegmentChunk($);_!=null&&_.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=_.byteLength,this.sourceBufferTaskQueue.append(_,a).then(C=>{if(a.aborted)n(c);else if(C)c.fedBytes+=_.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n(c)}}))}}}abortSegment(e){e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.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[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=_a(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?xe(this.destroyAbortController.signal,async function*(){const o=kr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||ee(t)||this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of i){if(d.time.to>=t||r>=e)break;d.status===te.FED&&u(d)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of i){if(d.time.from<t+this.forwardBufferTarget||r>e)break;d.status===te.FED&&u(d)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of i)if(h.status===te.NONE&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)){a=l,n=c;break}}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!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 i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>=1&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=_a(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ee(this.sourceBuffer)||ee(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.some(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Dt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Dt||(Dt={}));class dp{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new gt,this.subscription=new se,this.fetchManifest=xe(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Nt(a));const n=yield Ot(a,{signal:this.abortAllController.signal}).catch(ti);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=xe(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Dt.HEADER:Dt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,v;let p=r;const S=new Headers;if(n)switch(a){case Dt.HEADER:{S.append("Range",`${n.from}-${n.to}`);break}case Dt.PARAM:{const k=new URL(p,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),p=k.toString();break}default:M(a)}this.requestQuic&&(p=Nt(p));let g=this.abortAllController.signal;if(d){const k=new gt;if(this.subscription.add(V(G(this.abortAllController.signal,"abort"),G(d,"abort")).subscribe(()=>{try{k.abort()}catch(H){ti(H)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(H){ti(H)}g=k.signal}const T=fe(),I=yield Ot(p,{priority:u,headers:S,signal:g}).catch(ti),$=fe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-T),!I)return null;if(!I.ok||!I.body)return Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`));this.onHeadersReceived(I.headers);const _=parseInt((h=I.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!_){const k=yield I.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(k.byteLength,fe()-$),o==null||o(new DataView(k),k.byteLength),k}if(!o&&!l)return I.arrayBuffer();const[C,j]=I.body.tee(),U=C.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(j));let N=0;const Q=new ArrayBuffer(_),B=new Uint8Array(Q),O=new DataView(Q);let z=!1;const J=k=>{z=!0,ti(k)},re=xe(g,async function*({done:k,value:H}){N===0&&this.lastRequestFirstBytes$.next(fe()-T),!g.aborted&&(k?o==null||o(O,N):H&&(B.set(H,N),N+=H.byteLength,o==null||o(O,N),yield U==null?void 0:U.read().then(re,J)))}.bind(this));return yield U==null?void 0:U.read().then(re,J),z?null:Q}.bind(this)),this.fetchByteRangeRepresentation=xe(this.abortAllController.signal,async function*(r,a,n){if(r.type!==De.BYTE_RANGE)return null;const{from:o,to:u}=r.initRange;let d=o,l=u,c=!1,h,f;r.indexRange&&(h=r.indexRange.from,f=r.indexRange.to,c=u+1===h,c&&(d=Math.min(h,o),l=Math.max(f,u))),d=Math.min(d,0);const v=yield this.fetch(r.url,{range:{from:d,to:l},priority:n,measureThroughput:!1});if(!v)return null;const p=new DataView(v,o-d,u-d+1);if(!a.validateData(p))throw new Error("Invalid media file");const S=a.parseInit(p);let g;if(c&&h!==void 0&&f!==void 0)g=new DataView(v,h-d,f-h+1);else{const I=a.getIndexRange(S);if(I){const $=yield this.fetch(r.url,{range:I,priority:n,measureThroughput:!1});if(!$)return null;g=new DataView($)}}if(!g)throw new ReferenceError("No way to load representation index");const T=a.parseSegments(g,S);return{dataView:new DataView(v),segments:T}}.bind(this)),this.fetchTemplateRepresentation=xe(this.abortAllController.signal,async function*(r,a){if(r.type!==De.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{segments:r.segments.map(d=>({...d,status:te.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Hn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case De.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case De.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:M(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ti=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s},Ra=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ps=(s,e)=>{let t=s;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,u)=>ee(a)?o:ee(u)?a:a.padStart(parseInt(u,10),"0"))}return t},up=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,v,p,S,g,T,I,$,_,C,j,U,N,Q,B,O,z,J,re,k,H,de,pe,ve,_e,Me;const Z=new DOMParser().parseFromString(s,"application/xml"),be={video:[],audio:[],text:[]},$e=Z.children[0],Pe=$e.getElementsByTagName("Period")[0],ft=Pe.children;let Ue;const at=$e.getAttribute("mediaPresentationDuration"),pt=Pe.getAttribute("duration");if(at)Ue=Ra(at);else if(pt){const Fe=Ra(pt);A(Fe)&&(Ue=Fe)}let Gt=0;const _t=(i=(t=$e.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Xn=_t.includes(Qi.WEBM_AS_IN_FFMPEG)||_t.includes(Qi.WEBM_AS_IN_SPEC)?Bt.WEBM:Bt.MP4;for(const Fe of ft){const vi=Fe.getAttribute("mimeType"),Zn=Fe.getAttribute("codecs"),br=(r=Fe.getAttribute("contentType"))!==null&&r!==void 0?r:vi==null?void 0:vi.split("/")[0],eo=(n=(a=Fe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],to=Fe.querySelectorAll("Representation"),io=Fe.querySelector("SegmentTemplate");if(br!=="text")for(const ye of to){const qt=(o=ye.getAttribute("mimeType"))!==null&&o!==void 0?o:vi,yr=(d=(u=ye.getAttribute("codecs"))!==null&&u!==void 0?u:Zn)!==null&&d!==void 0?d:"",Si=(c=(l=ye.getAttribute("contentType"))!==null&&l!==void 0?l:qt==null?void 0:qt.split("/")[0])!==null&&c!==void 0?c:br,so=(f=(h=Fe.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],ro=parseInt((v=ye.getAttribute("width"))!==null&&v!==void 0?v:"",10),Tr=parseInt((p=ye.getAttribute("height"))!==null&&p!==void 0?p:"",10),Er=parseInt((S=ye.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,$r=(g=ye.getAttribute("frameRate"))!==null&&g!==void 0?g:"",ao=(T=ye.getAttribute("quality"))!==null&&T!==void 0?T:void 0,no=$r?Sr($r):void 0,oo=(I=ye.getAttribute("id"))!==null&&I!==void 0?I:(Gt++).toString(10),uo=Si==="video"?`${Tr}p`:Si==="audio"?`${Er}Kbps`:yr,lo=`${oo}@${uo}`,co=(C=(_=($=ye.querySelector("BaseURL"))===null||$===void 0?void 0:$.textContent)===null||_===void 0?void 0:_.trim())!==null&&C!==void 0?C:"",wr=new URL(co,e).toString(),ho=[..._t,...eo,...so];let ts;const fo=ye.querySelector("SegmentBase"),mt=(j=ye.querySelector("SegmentTemplate"))!==null&&j!==void 0?j:io;if(fo){const Yt=(N=(U=ye.querySelector("SegmentBase Initialization"))===null||U===void 0?void 0:U.getAttribute("range"))!==null&&N!==void 0?N:"",[jt,ss]=Yt.split("-").map(vt=>parseInt(vt,10)),zt={from:jt,to:ss},Wt=(Q=ye.querySelector("SegmentBase"))===null||Q===void 0?void 0:Q.getAttribute("indexRange"),[rs,gi]=Wt?Wt.split("-").map(vt=>parseInt(vt,10)):[],Qt=Wt?{from:rs,to:gi}:void 0;ts={type:De.BYTE_RANGE,url:wr,initRange:zt,indexRange:Qt}}else if(mt){const Yt={representationId:(B=ye.getAttribute("id"))!==null&&B!==void 0?B:void 0,bandwidth:(O=ye.getAttribute("bandwidth"))!==null&&O!==void 0?O:void 0},jt=parseInt((z=mt.getAttribute("timescale"))!==null&&z!==void 0?z:"",10),ss=(J=mt.getAttribute("initialization"))!==null&&J!==void 0?J:"",zt=mt.getAttribute("media"),Wt=(k=parseInt((re=mt.getAttribute("startNumber"))!==null&&re!==void 0?re:"",10))!==null&&k!==void 0?k:1,rs=Ps(ss,Yt);if(!zt)throw new ReferenceError("No media attribute in SegmentTemplate");const gi=(H=mt.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],Qt=[];if(gi.length){let vt=Wt,St=0;for(const Jt of gi){const At=parseInt((de=Jt.getAttribute("d"))!==null&&de!==void 0?de:"",10)*1e3,Kt=parseInt((pe=Jt.getAttribute("r"))!==null&&pe!==void 0?pe:"",10)||0,Xt=(_e=parseInt((ve=Jt.getAttribute("t"))!==null&&ve!==void 0?ve:"",10))!==null&&_e!==void 0?_e:void 0;for(let _r=0;_r<Kt+1;_r++){const po=Ps(zt,{...Yt,segmentNumber:vt.toString(10),segmentTime:Xt.toString(10)}),mo=Xt?Xt/jt:St;St+=At/jt;const vo=St;vt++,Qt.push({time:{from:mo,to:vo},url:po})}}}else if(A(Ue)){const St=parseInt((Me=mt.getAttribute("duration"))!==null&&Me!==void 0?Me:"",10)/jt*1e3,Jt=Math.ceil(Ue/St);let At=0;for(let Kt=1;Kt<Jt;Kt++){const Xt=Ps(zt,{...Yt,segmentNumber:Kt.toString(10),segmentTime:At.toString(10)});Qt.push({time:{from:At,to:At+St},url:Xt}),At+=St}}ts={type:De.TEMPLATE,baseUrl:wr,initUrl:rs,segments:Qt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Si||!qt)continue;const is={video:Ie.VIDEO,audio:Ie.AUDIO,text:Ie.TEXT}[Si];is&&be[is].push({id:lo,kind:is,segmentReference:ts,profiles:ho,duration:Ue,bitrate:Er,mime:qt,codecs:yr,width:ro,height:Tr,fps:no,quality:ao})}}return{duration:Ue,container:Xn,representations:be}},lp=["timeupdate","progress","play","seeked","stalled"];var Re;(function(s){s.NONE="none",s.MANIFEST_LOADED="manifest_loaded",s.REPRESENTATION_SELECTED="representation_selected"})(Re||(Re={}));let cp=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new le(Re.NONE),this.currentVideoRepresentation$=new b(void 0),this.error$=new L,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new gt,this.initManifest=xe(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(Re.MANIFEST_LOADED);const r=yield this.fetcher.fetchManifest(i).catch(o=>this.error$.next({id:"LoadManifest",category:x.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return null;let a;try{a=up(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:x.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return null;const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};return this.manifest={...a,representations:hi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(Re.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:x.PARSER,message:"No playable video representations"}),this.manifest}.bind(this)),this.initRepresentations=xe(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.state$.startTransitionTo(Re.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Pa(Ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],A(i)&&(this.audioBufferManager=new Pa(Ie.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),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 a=V(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=V(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(V(this.forceEnded$,Ke({allBuffersFull:a,someBufferEnded:n}).pipe(q(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:x.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(V(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),A(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&A(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Re.REPRESENTATION_SELECTED),P(this.element),this.subscription.add(V(...lp.map(o=>G(this.element,o)),G(window,"online")).subscribe(this.tick,o=>{this.error$.next({id:"DashVKPlayer",category:x.WTF,message:"Internal logic error",thrown:o})})),this.subscription.add(G(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(G(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&wa(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=go(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:x.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new dp({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async switchRepresentation(e,t){const i={[Ie.VIDEO]:this.videoBufferManager,[Ie.AUDIO]:this.audioBufferManager,[Ie.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),wa(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/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(Re.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 i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));const hp=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?pi(a):void 0)!==null&&n!==void 0?n:$t({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},fp=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=We(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:We(s,-1)};class pp{constructor(e){this.subscription=new se,this.videoState=new le(ce.STOPPED),this.elementSize$=new b(void 0),this.textTracksManager=new je,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new $f,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===F.Requested&&(r==null?void 0:r.to)!==m.PAUSED&&t!==ce.STOPPED&&i!==m.STOPPED&&this.seek(a.position,a.forcePrecise),i===m.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.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(ce.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}switch(t){case ce.READY:i===m.PAUSED?(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case ce.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return M(t)}}},this.params=e,this.video=st(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new cp({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=rt(this.video),r=u=>{e.error$.next({id:"DashVKProvider",category:x.WTF,message:"DashVKProvider internal logic error",thrown:u})},a=(u,d)=>this.subscription.add(u.subscribe(d,r));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.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(q(A),ge(),yt(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wt(this.video,t.isLooped,r)),this.subscription.add(it(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ct(this.video,t.playbackRate,i.playbackRateState$,r)),a(zi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,m.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(q(({to:u})=>u===Re.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(ce.READY)}));const n=u=>e.error$.next({id:"RepresentationSwitch",category:x.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(V(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,G(this.video,"progress")).subscribe(()=>{var u,d,l,c,h,f,v,p;const S=this.player.state$.getState(),g=this.player.state$.getTransition();if(S===Re.NONE||!this.videoTracks.length)return;const T=S===Re.MANIFEST_LOADED&&!g,I=S===Re.REPRESENTATION_SELECTED&&!g,$=t.autoVideoTrackSwitching.getState(),_=t.videoTrack.getState(),C=(u=this.videoTracks.find(({track:{id:J}})=>J===_))===null||u===void 0?void 0:u.track,j=e.currentVideoTrack$.getValue(),U=Lt(this.video.buffered,this.video.currentTime*1e3),N=$?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,Q=Math.min(U/Math.min(N,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),B=Math.max(C&&!$&&(l=(d=this.audioRepresentations.get(C.id))===null||d===void 0?void 0:d.bitrate)!==null&&l!==void 0?l:0,j&&(h=(c=this.audioRepresentations.get(j.id))===null||c===void 0?void 0:c.bitrate)!==null&&h!==void 0?h:0),O=fi(this.videoTracks.map(({track:J})=>J),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:B,forwardBufferHealth:Q,current:j,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),z=$?O!=null?O:C:C!=null?C:O;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState($),this.player.setBufferTarget(N)),T){const J=z&&((f=this.videoTracks.find(({track:re})=>re===z))===null||f===void 0?void 0:f.representation);P(J),this.player.initRepresentations(J.id,(v=this.audioRepresentations.get(J.id))===null||v===void 0?void 0:v.id)}else if(I){const J=z&&((p=this.videoTracks.find(({track:re})=>re===z))===null||p===void 0?void 0:p.representation);if(J){const re=this.audioRepresentations.get(J.id);this.player.switchRepresentation(Ie.VIDEO,J.id).catch(n),re&&this.player.switchRepresentation(Ie.AUDIO,re.id).catch(n)}}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(me(),w(u=>{var d;return u&&((d=this.videoTracks.find(({representation:{id:l}})=>l===u))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((r,a)=>a.bitrate-r.bitrate),i=Array.from(e.representations.video).sort((r,a)=>a.bitrate-r.bitrate);for(const r of i){const a=hp(r);if(a){this.videoTracks.push({track:a,representation:r});const n=fp(t,i,r);n&&this.audioRepresentations.set(r.id,n)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:r})=>r))}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(){ht(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}}const mp=5e3,ze={};var ie;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ie||(ie={}));const Ii=(s,e)=>new di(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class vp{constructor(e){this.subscription=new se,this.videoState=new le(ie.INITIALIZING),this.textTracksManager=new je,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==ie.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===F.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:M(t)}break;case m.PLAYING:switch(t){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:M(t)}break;case m.PAUSED:switch(t){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED);break;case ie.PLAYING:this.pause();break;default:M(t)}break;default:M(i)}},this.video=st(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(we(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=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:x.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),mp);import("hls.js").then(r=>{e||(ze.Hls=r.default,ze.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ze.Hls,"hls.js not loaded"),this.hls=new ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ie.STOPPED)}subscribe(){P(ze.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:x.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=rt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(wt(this.video,e.isLooped,i)),this.subscription.add(it(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ct(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Ii(this.hls,ze.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:x.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),R(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),a(Ii(this.hls,ze.Events.MANIFEST_PARSED).pipe(w(({levels:d})=>d.reduce((l,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:p,height:S}=c,g=(f=pi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:$t({width:p,height:S});if(!g)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:v.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:p,height:S},fps:T};return this.trackLevels.set(v,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(Ii(this.hls,ze.Events.LEVEL_LOADING).pipe(w(({url:d})=>we(d))),t.hostname$),this.subscription.add(qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=Ii(this.hls,ze.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(q(A)).subscribe(t.currentVideoTrack$,i),this.subscription.add(qe(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(ee(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(w(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=V(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(ie.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ie.PLAYING),await ht(this.video)||(this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ie.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(ie.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0)}}const Ia="X-Playback-Duration";var Da=async s=>{const e=await Ot(s,{method:"HEAD"});return e.headers.has(Ia)?parseInt(e.headers.get(Ia),10):void 0};const Sp=s=>{let e=null;if(s.QUALITY&&(e=pi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=$t({width:t,height:i})}return e!=null?e:null},Qn=async(s,e=s)=>{var t;const a=(await(await Ot(s)).text()).split(`
8
+ `),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=hi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Sp(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let p;if(l.RESOLUTION){const[g,T]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&T&&(p={width:g,height:T})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:f,size:p,fps:v})}return n};var ae;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ae||(ae={}));class gp{constructor(e){var t;this.subscription=new se,this.videoState=new le(ae.STOPPED),this.textTracksManager=new je,this.manifests$=new b([]),this.liveOffset=new vr,this.manifestStartTime$=new b(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===m.STOPPED){r!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(ae.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===F.None&&this.params.desiredState.seekState.setState({state:F.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&l.state===F.Requested){this.videoState.startTransitionTo(ae.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ae.READY:a===m.PAUSED?(this.videoState.setState(ae.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed());return;case ae.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case ae.PAUSED:a===m.PLAYING?(this.videoState.startTransitionTo(ae.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())):(n==null?void 0:n.to)===m.PAUSED&&(R(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case ae.CHANGING_MANIFEST:break;default:return M(r)}},this.params=e,this.video=st(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:oe.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Qn(xt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:x.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.maxSeekBackTime$=new b((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:x.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=rt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));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(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ae.READY&&this.videoState.setState(ae.READY),this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(me(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&A(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ae.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===F.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Ke({startTime:this.manifestStartTime$.pipe(q(A)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(Oe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(ee(e))return;const t=xt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Da(t).then(i=>{var r;if(!ee(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(ee(a)||!isFinite(a))try{Ot(t).then(n=>n.text()).then(n=>{var o;const u=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(u){const d=new URL(u,t).toString();Da(d).then(l=>{ee(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var ue;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ue||(ue={}));class bp{constructor(e){this.subscription=new se,this.videoState=new le(ue.STOPPED),this.textTracksManager=new je,this.manifests$=new b([]),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===m.STOPPED){i!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===ue.STOPPED){this.videoState.startTransitionTo(ue.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(ue.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===F.None&&this.params.desiredState.seekState.setState({state:F.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&d.state===F.Requested&&this.seek(d.position),i){case ue.READY:r===m.PAUSED?(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed());return;case ue.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case ue.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;case ue.CHANGING_MANIFEST:break;default:return M(i)}},this.params=e,this.video=st(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:oe.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),Qn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:x.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:x.WTF,message:"HlsProvider internal logic error",thrown:o})},r=rt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));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(wt(this.video,t.isLooped,i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ue.READY&&this.videoState.setState(ue.READY),this.videoState.getState()===ue.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&A(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ue.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===F.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();ee(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var he;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(he||(he={}));class yp{constructor(e){this.subscription=new se,this.videoState=new le(he.STOPPED),this.trackUrls={},this.textTracksManager=new je,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.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(he.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===he.STOPPED){this.videoState.startTransitionTo(he.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===F.None&&this.params.desiredState.seekState.setState({state:F.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==m.PAUSED&&o.state===F.Requested&&this.seek(o.position),t){case he.READY:i===m.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed());return;case he.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case he.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return M(t)}},this.params=e,this.video=st(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:x.WTF,message:"MpegProvider internal logic error",thrown:o})},r=rt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));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(wt(this.video,t.isLooped,i)),this.subscription.add(it(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===he.READY&&this.videoState.setState(he.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&A(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(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();P(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];P(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=Nt(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(we(r))}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Ca=["stun:videostun.mycdn.me:80"],Tp=1e3,Ep=3,Rs=()=>null;class $p{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Rs,this.externalStopCallback=Rs,this.externalErrorCallback=Rs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.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}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Ca}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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:x.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),Tp)}normalizeOptions(e={}){const t={stunServerList:Ca,maxRetryNumber:Ep,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ne;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ne||(ne={}));class wp{constructor(e){this.videoState=new le(ne.STOPPED),this.maxSeekBackTime$=new b(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case ne.READY:i===m.PAUSED?(this.videoState.setState(ne.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case ne.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return M(t)}},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=st(e.container),this.liveStreamClient=new $p(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,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:x.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};V(this.videoState.stateChangeStarted$.pipe(w(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=rt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));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(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===ne.READY&&this.videoState.setState(ne.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(it(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ne.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case ne.READY:break;case ne.PAUSED:t.playbackState.setState(m.PAUSED);break;case ne.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return M(n.to)}},i)).add(V(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Oe(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:oe.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ne.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:x.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ht(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class La{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 _p=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Is,Ds,Cs,Ls,xs,Os,Di,Ns,Ci,Bs,Li,Ms,xi,Us,Oi,Fs;const Jn=_p(),ot=document.createElement("video"),nt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Ds=(Is=window.SourceBuffer)===null||Is===void 0?void 0:Is.prototype)===null||Ds===void 0?void 0:Ds.appendBuffer)),hls:Boolean(((Cs=ot.canPlayType)===null||Cs===void 0?void 0:Cs.call(ot,"application/x-mpegurl"))||((Ls=ot.canPlayType)===null||Ls===void 0?void 0:Ls.call(ot,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},He={mp4:Boolean((xs=ot.canPlayType)===null||xs===void 0?void 0:xs.call(ot,"video/mp4")),webm:Boolean((Os=ot.canPlayType)===null||Os===void 0?void 0:Os.call(ot,"video/webm"))},dt={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((Bs=(Ci=window.MediaSource)===null||Ci===void 0?void 0:Ci.isTypeSupported)===null||Bs===void 0?void 0:Bs.call(Ci,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Ms=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||Ms===void 0?void 0:Ms.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((Fs=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||Fs===void 0?void 0:Fs.call(Oi,'audio/webm; codecs="opus"'))},ii=(dt.h264||dt.h265)&&dt.aac,es=nt.hls&&He.mp4,Ap=Boolean(window.WebSocket),kp=()=>Object.keys(dt).filter(s=>dt[s]),Pp=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return nt.mse&&He.mp4&&ii;case y.DASH_SEP:return nt.mse&&He.mp4&&ii;case y.DASH_WEBM:return nt.mse&&He.webm&&dt.vp9&&dt.opus;case y.DASH_LIVE:return nt.mse&&He.mp4&&ii;case y.DASH_ONDEMAND:return nt.mse&&He.mp4&&ii;case y.HLS:case y.HLS_LIVE:case y.HLS_ONDEMAND:return es||e&&nt.mse&&He.mp4&&ii;case y.MPEG:return He.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return nt.webrtc&&Ap&&dt.h264&&(He.mp4||He.webm);default:return M(t)}}),Rp=()=>Jn?[y.MPEG,y.DASH_WEBM,y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:es?[y.DASH_WEBM,y.DASH_SEP,y.HLS,y.HLS_ONDEMAND,y.DASH_ONDEMAND,y.MPEG,y.DASH]:[y.DASH_WEBM,y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],Ip=()=>Jn?[y.HLS_LIVE,y.WEB_RTC_LIVE,y.DASH_LIVE]:es?[y.WEB_RTC_LIVE,y.HLS_LIVE,y.DASH_LIVE]:[y.WEB_RTC_LIVE,y.DASH_LIVE,y.HLS_LIVE],xa=s=>s?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var Dp=s=>new di(e=>{const t=new se,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$,n=new L;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Oa={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Cp={cacheDuration:12e4},Lp={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},xp={maxPausedTime:3e4},Op={maxPausedTime:3e4};class Np{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),autoVideoTrackLimitingAvailable$:new b(!1),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new b(void 0),liveTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),element$:new b(void 0)},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Pp([...Ip(),...Rp()],this.params.tuning.useHlsJs).filter(n=>A(e.sources[n])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(n=>!i.includes(n)),...t.filter(n=>i.includes(n))]:t;this.screenFormatsIterator=new La(r);const a=[...xa(!0),...xa(!1)];this.chromecastFormatsIterator=new La(a.filter(n=>A(e.sources[n])))}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(ee(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:x.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;P(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,i=this.params.desiredState.seekState.getState(),r=i.state!==F.None;this.params.desiredState.seekState.setState({state:F.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return M(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new zf({...n,source:o,config:Cp})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new Af({...n,source:o,format:e,config:Op}):new pp({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),es||!this.params.tuning.useHlsJs?new bp({...n,source:o}):new vp({...n,source:o})}case y.HLS_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new gp({...n,source:o,config:xp})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new yp({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Hf({...n,source:o,config:Lp})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new wp({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return M(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Wh({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return M(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return M(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case Ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return M(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return hi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,i=0;return e.add(V(this.providerOutput.error$,Dp({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Oa.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(q(({type:r})=>r!==void 0))}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:x.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(q(({to:a})=>a===m.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===x.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=i<Oa.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Na=(s,e,t)=>t*e+(1-t)*s;class Ba{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 b(e.initial),this.debounced$=new b(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${i}`),this.smoothedSeries$=new Ge(`smoothed_${i}`),this.reportedSeries$=new Ge(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);t/=i;const r=Math.sqrt(t),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=Na(this.slow,e,this.params.emaAlphaSlow),this.fast=Na(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)&&(ee(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 Ce;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(Ce||(Ce={}));const Kn=new Map;let bt=Ce.RUNTIME;const Vs=`vk-videoplayer-dummy-key-${Math.random()}`,Bp=()=>{try{localStorage.setItem(Vs,"test"),localStorage.removeItem(Vs),bt=Ce.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Vs),bt=Ce.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)bt=Ce.RUNTIME;else throw e}else throw s}};Bp();const Mp=s=>{var e,t;switch(bt){case Ce.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case Ce.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case Ce.RUNTIME:return Kn.get(s);default:M(bt)}},Ma=(s,e)=>{switch(bt){case Ce.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.RUNTIME:return void Kn.set(s,e);default:M(bt)}},Up=5e3,Ua="one_video_throughput",Fa="one_video_rtt",Ze=window.navigator.connection,Va=()=>{const s=Ze==null?void 0:Ze.downlink;if(A(s)&&s!==10)return s*1e3},Ha=()=>{const s=Ze==null?void 0:Ze.rtt;if(A(s)&&s!==3e3)return s},Ga=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class ai{constructor(e){var t,i;this.subscription=new se,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ai.load(Ua)||(e.useBrowserEstimation?Va():void 0)||Up,a=(i=(t=ai.load(Fa))!==null&&t!==void 0?t:e.useBrowserEstimation?Ha():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(Ga(r,a,e.rttPenaltyRequestSize)),this.throughput=new Ba({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new Ba({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const n=()=>{const u=Va();u&&this.throughput.next(u);const d=Ha();A(d)&&this.rtt.next(d)};Ze&&"onchange"in Ze&&this.subscription.add(G(Ze,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ma(Ua,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ma(Fa,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ke({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>Ga(n,o,e.rttPenaltyRequestSize)),q(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=fe();const r=new se;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(G(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=fe()}));break;case 1:case 0:r.add(G(e,"loadstart").subscribe(()=>{t=0,i=fe()}));break}r.add(G(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=fe(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=fe();let a=0,n=fe();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{d?(this.addRawSpeed(i,fe()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&fe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,fe()-n,this.concurrentDownloads.size),a=0,n=fe()),await(t==null?void 0:t.read().then(u,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(ai.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Mp(e);if(A(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const qa={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}},Fp=s=>{const e={};for(const t of Object.keys(qa)){const i=qa[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var Vp=({seekState:s,position$:e})=>V(s.stateChangeEnded$.pipe(w(({to:t})=>{var i;return t.state===F.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),q(A)),e.pipe(q(()=>s.getState().state===F.None))),Hp=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const Ya=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:r})=>new di(a=>{let n;const o=s.transitionEnded$.pipe(q(f=>(f.from===m.PAUSED||f.from===m.STOPPED)&&f.to===m.PLAYING)),u=s.stateChangeEnded$.pipe(q(f=>f.from===m.PLAYING&&f.to===m.PAUSED)),d=e.stateChangeEnded$.pipe(q(({to:f})=>{var v,p;return f.state===F.Requested&&((p=(v=s.getTransition())===null||v===void 0?void 0:v.from)!==null&&p!==void 0?p:s.getState())===m.PLAYING})),l=e.stateChangeEnded$.pipe(q(({from:f,to:v})=>{var p,S;return f.state===F.Applying&&v.state===F.None&&((S=(p=s.getTransition())===null||p===void 0?void 0:p.from)!==null&&S!==void 0?S:s.getState())===m.PLAYING})),c=V(o,l).pipe(w(()=>r.getValue()),q(A)),h=V(V(u,d,t),i).pipe(w(()=>r.getValue()),q(A));return new se().add(c.subscribe(f=>{n=f})).add(h.subscribe(f=>{if(ee(n)||n===f)return;const v={from:n,to:f};n=void 0,a.next(v)}))});class Wp{constructor(e={}){if(this.subscription=new se,this.logger=new bo,this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(m.STOPPED),seekState:new le({state:F.None}),volume:new le({volume:1,muted:!1}),videoTrack:new le(void 0),autoVideoTrackSwitching:new le(!0),autoVideoTrackLimits:new le({}),isLooped:new le(!1),playbackRate:new le(1),externalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({})},this.info={playbackState$:new b(m.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),liveTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),chromecastState$:new b(Ee.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0)},this.events={inited$:new L,started$:new L,willPause$:new L,willResume$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new b(void 0),enableDebugTelemetry$:new b(!1),dumpTelemetry:yf},this.initLogs(),this.tuning=Fp(e),this.chromecastInitializer=new wo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ai(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:x.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Hp(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Np({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?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 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()!==m.PLAYING&&e.startTransitionTo(m.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==m.PAUSED&&e.startTransitionTo(m.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==m.STOPPED&&e.startTransitionTo(m.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:F.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()===Ee.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()===Ee.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.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(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(ee(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===F.None?void 0:t.position;return A(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(V(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(w(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(()=>!this.isPlaybackStarted),q(e=>e.to===m.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case m.PAUSED:this.events.willPause$.next();break;case m.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=fe(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const u=this.desiredState.seekState.getState();u.state===F.Requested?this.desiredState.seekState.setState({...u,state:F.Applying}):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:x.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===F.Applying&&(this.desiredState.seekState.setState({state:F.None}),this.events.seeked$.next())})).add(e.current$.pipe(w(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(w(u=>u.destination),me()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(u=>u.map(({quality:d})=>d).sort((d,l)=>Yi(d)?1:Yi(l)?-1:Ui(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate);const d=e.providerOutput.element$.getValue();d&&this.info.intrinsicVideoSize$.next({width:d.videoWidth,height:d.videoHeight})})).add(e.providerOutput.hostname$.pipe(me()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(me()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(me()).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(w(u=>u?{start:u.from,end:u.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(w(u=>u.muted),me()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(u=>u.volume),me()).subscribe(this.info.volume$)).add(Vp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(V(e.providerOutput.endedEvent$.pipe(yt(!0)),e.providerOutput.seekedEvent$.pipe(yt(!1))).pipe(me()).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(w(u=>({id:"NoProviders",category:x.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(ge(),w(()=>fe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),w(()=>fe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),w(()=>fe()-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 b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new b(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(({to:u})=>u===m.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=V(e.providerOutput.isBuffering$,t,i).pipe(w(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||i.getValue();return u&&!d}),me());this.subscription.add(a.subscribe(u=>{u?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const n=new se;this.subscription.add(n);const o=V(G(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(q(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(me()).subscribe(u=>{switch(P(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new b(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(Ya({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe(w(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Ya({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(w(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}})}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(w(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 se;this.subscription.add(t),this.subscription.add(e.current$.pipe(me((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=fi(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(V(this.desiredState.videoTrack.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(w(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;P(this.providerContainer),P(t),bf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>gf(i)),this.providerContainer.current$.subscribe(({type:i})=>ki("provider",i)),t.duration$.subscribe(i=>ki("duration",i)),t.availableVideoTracks$.pipe(q(i=>!!i.length),ge()).subscribe(i=>ki("tracks",i)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),t.position$.subscribe(new Ge("position")),t.currentVideoTrack$.pipe(w(i=>i==null?void 0:i.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),t.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(i=>this.subscription.add(i)),ki("codecs",kp())}}const Qp=`${Eo}@${To}`;export{Ee as ChromecastState,ni as HttpConnectionType,Xp as Observable,m as PlaybackState,Wp as Player,Qp as SDK_VERSION,Zp as Subject,em as Subscription,tm as ValueSubject,y as VideoFormat,oe as VideoQuality};