@vkontakte/videoplayer-core 2.0.103 → 2.0.104

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 (130) hide show
  1. package/es2015.cjs.js +73 -27
  2. package/es2015.esm.js +72 -26
  3. package/es2018.cjs.js +73 -27
  4. package/es2018.esm.js +72 -26
  5. package/esnext.cjs.js +75 -29
  6. package/esnext.esm.js +73 -27
  7. package/evergreen.esm.js +73 -27
  8. package/package.json +7 -7
  9. package/types/enums/AndroidPreferredFormat.d.ts +8 -0
  10. package/types/enums/WebmCodecStrategy.d.ts +7 -0
  11. package/types/env.d.ts +1 -0
  12. package/types/index.d.ts +12 -0
  13. package/types/player/Player.d.ts +173 -0
  14. package/{index.d.ts → types/player/types.d.ts} +64 -391
  15. package/types/player/utils/optimisticPosition.d.ts +12 -0
  16. package/types/player/utils/selectContainer.d.ts +3 -0
  17. package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +31 -0
  18. package/types/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +23 -0
  19. package/types/providers/ChromecastProvider/index.d.ts +33 -0
  20. package/types/providers/DashLiveProvider/DashLiveProvider.d.ts +37 -0
  21. package/types/providers/DashLiveProvider/index.d.ts +2 -0
  22. package/types/providers/DashLiveProvider/types.d.ts +21 -0
  23. package/types/providers/DashLiveProvider/utils/FilesFetcher.d.ts +25 -0
  24. package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +143 -0
  25. package/types/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +33 -0
  26. package/types/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +42 -0
  27. package/types/providers/DashProvider/baseDashProvider.d.ts +52 -0
  28. package/types/providers/DashProvider/consts.d.ts +1 -0
  29. package/types/providers/DashProvider/dashCmafLiveProvider.d.ts +8 -0
  30. package/types/providers/DashProvider/dashProvider.d.ts +6 -0
  31. package/types/providers/DashProvider/index.d.ts +2 -0
  32. package/types/providers/DashProvider/lib/buffer.d.ts +103 -0
  33. package/types/providers/DashProvider/lib/fetcher.d.ts +51 -0
  34. package/types/providers/DashProvider/lib/parsers/mpd.d.ts +3 -0
  35. package/types/providers/DashProvider/lib/parsers/mpeg/BoxModel.d.ts +20 -0
  36. package/types/providers/DashProvider/lib/parsers/mpeg/BoxParser.d.ts +21 -0
  37. package/types/providers/DashProvider/lib/parsers/mpeg/BoxTypeEnum.d.ts +26 -0
  38. package/types/providers/DashProvider/lib/parsers/mpeg/box.d.ts +79 -0
  39. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/equi.d.ts +21 -0
  40. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/ftyp.d.ts +17 -0
  41. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +22 -0
  42. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdat.d.ts +15 -0
  43. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +7 -0
  44. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mfhd.d.ts +11 -0
  45. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +7 -0
  46. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +7 -0
  47. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +7 -0
  48. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/prhd.d.ts +16 -0
  49. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +7 -0
  50. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sidx.d.ts +48 -0
  51. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/st3d.d.ts +23 -0
  52. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +7 -0
  53. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfdt.d.ts +17 -0
  54. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfhd.d.ts +22 -0
  55. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tkhd.d.ts +42 -0
  56. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +7 -0
  57. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +7 -0
  58. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trun.d.ts +31 -0
  59. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/unknown.d.ts +6 -0
  60. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +6 -0
  61. package/types/providers/DashProvider/lib/parsers/mpeg/fullBox.d.ts +15 -0
  62. package/types/providers/DashProvider/lib/parsers/mpeg/isobmff.d.ts +12 -0
  63. package/types/providers/DashProvider/lib/parsers/webm/ebml.d.ts +76 -0
  64. package/types/providers/DashProvider/lib/parsers/webm/webm.d.ts +3 -0
  65. package/types/providers/DashProvider/lib/player.d.ts +75 -0
  66. package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +18 -0
  67. package/types/providers/DashProvider/lib/types.d.ts +156 -0
  68. package/types/providers/DashProvider/lib/utils.d.ts +14 -0
  69. package/types/providers/HlsJsProvider/index.d.ts +24 -0
  70. package/types/providers/HlsLiveProvider/index.d.ts +30 -0
  71. package/types/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +3 -0
  72. package/types/providers/HlsProvider/index.d.ts +21 -0
  73. package/types/providers/HlsProvider/manifestDataExtractor.d.ts +21 -0
  74. package/types/providers/MpegProvider/index.d.ts +20 -0
  75. package/types/providers/ProviderContainer/index.d.ts +42 -0
  76. package/types/providers/ProviderContainer/types.d.ts +20 -0
  77. package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +20 -0
  78. package/types/providers/ProviderContainer/utils/playbackHangup.d.ts +12 -0
  79. package/types/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +188 -0
  80. package/types/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +60 -0
  81. package/types/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +9 -0
  82. package/types/providers/types.d.ts +83 -0
  83. package/types/providers/utils/HTMLVideoElement/DroppedFramesManager.d.ts +44 -0
  84. package/types/providers/utils/HTMLVideoElement/TextTrackManager.d.ts +30 -0
  85. package/types/providers/utils/HTMLVideoElement/clear.d.ts +1 -0
  86. package/types/providers/utils/HTMLVideoElement/destroy.d.ts +1 -0
  87. package/types/providers/utils/HTMLVideoElement/forcePlay.d.ts +7 -0
  88. package/types/providers/utils/HTMLVideoElement/observable.d.ts +25 -0
  89. package/types/providers/utils/HTMLVideoElement/pool.d.ts +2 -0
  90. package/types/providers/utils/HTMLVideoElement/surface.d.ts +2 -0
  91. package/types/providers/utils/LiveOffset/index.d.ts +14 -0
  92. package/types/providers/utils/LiveOffset/types.d.ts +10 -0
  93. package/types/providers/utils/addQuicParam.d.ts +2 -0
  94. package/types/providers/utils/extractConnectionHeaders.d.ts +6 -0
  95. package/types/providers/utils/generateLiveUrl.d.ts +9 -0
  96. package/types/providers/utils/okQualityStringToVideoQuality.d.ts +3 -0
  97. package/types/providers/utils/parseFps.d.ts +1 -0
  98. package/types/providers/utils/syncDesiredState.d.ts +12 -0
  99. package/types/providers/utils/syncPlaybackState.d.ts +4 -0
  100. package/types/utils/3d/Camera3D.d.ts +14 -0
  101. package/types/utils/3d/CameraRotationManager.d.ts +62 -0
  102. package/types/utils/3d/Scene3D.d.ts +132 -0
  103. package/types/utils/3d/types.d.ts +25 -0
  104. package/types/utils/StateMachine/StateMachine.d.ts +19 -0
  105. package/types/utils/StateMachine/types.d.ts +60 -0
  106. package/types/utils/StatefulIterator/index.d.ts +13 -0
  107. package/types/utils/ThroughputEstimator.d.ts +25 -0
  108. package/types/utils/addScript.d.ts +2 -0
  109. package/types/utils/autoSelectVideoTrack.d.ts +26 -0
  110. package/types/utils/buffer/getBufferedRangeForPosition.d.ts +3 -0
  111. package/types/utils/buffer/getForwardBufferDuration.d.ts +3 -0
  112. package/types/utils/buffer/getTotalBufferDuration.d.ts +3 -0
  113. package/types/utils/buffer/isPositionBuffered.d.ts +3 -0
  114. package/types/utils/changePlaybackRate.d.ts +2 -0
  115. package/types/utils/hostnameFromUrl.d.ts +2 -0
  116. package/types/utils/isInPiP.d.ts +1 -0
  117. package/types/utils/link.d.ts +2 -0
  118. package/types/utils/mediaSource.d.ts +8 -0
  119. package/types/utils/observeElementVisibility.d.ts +3 -0
  120. package/types/utils/playbackTelemetry.d.ts +12 -0
  121. package/types/utils/setStateWithSubscribe.d.ts +3 -0
  122. package/types/utils/smoothedValue/baseSmoothedValue.d.ts +18 -0
  123. package/types/utils/smoothedValue/emaAndMaSmoothedValue.d.ts +7 -0
  124. package/types/utils/smoothedValue/emaTopExtremumValue.d.ts +10 -0
  125. package/types/utils/smoothedValue/smoothedValueFactory.d.ts +6 -0
  126. package/types/utils/smoothedValue/twoEmaSmoothedValue.d.ts +8 -0
  127. package/types/utils/smoothedValue/types.d.ts +26 -0
  128. package/types/utils/smoothedValue/utils.d.ts +3 -0
  129. package/types/utils/tuningConfig.d.ts +164 -0
  130. package/types/utils/videoFormat.d.ts +2 -0
package/es2015.cjs.js CHANGED
@@ -1,46 +1,92 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.103
3
- * Tue, 18 Jun 2024 13:19:48 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-103/doc/
2
+ * @vkontakte/videoplayer-core v2.0.104
3
+ * Mon, 24 Jun 2024 13:01:09 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
5
5
  */
6
- "use strict";var Fu=Object.create;var qa=Object.defineProperty;var Uu=Object.getOwnPropertyDescriptor;var ju=Object.getOwnPropertyNames;var Hu=Object.getPrototypeOf,Gu=Object.prototype.hasOwnProperty;var Yu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ju(e))!Gu.call(i,s)&&s!==t&&qa(i,s,{get:()=>e[s],enumerable:!(r=Uu(e,s))||r.enumerable});return i};var qu=(i,e,t)=>(t=i!=null?Fu(Hu(i)):{},Yu(e||!i||!i.__esModule?qa(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js");const Vo="2.0.103";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var le;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(le||(le={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var N;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(N||(N={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip",i.INVISIBLE="invisible"})(exports.Surface||(exports.Surface={}));function G(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(h){try{u(r.next(h))}catch(c){o(c)}}function d(h){try{u(r.throw(h))}catch(c){o(c)}}function u(h){h.done?n(h.value):s(h.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function C(i){return this instanceof C?(this.v=i,this):new C(i)}function fe(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(v){c(n[0][3],v)}}function d(f){f.value instanceof C?Promise.resolve(f.value.v).then(u,h):c(n[0][2],f)}function u(f){l("next",f)}function h(f){l("throw",f)}function c(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var Wu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class zu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Wu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(Qu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),h=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(h)||h===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Qu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Nr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ur(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var $e=function(i){try{return!!i()}catch(e){return!0}},Ku=$e,cr=!Ku(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Fo=cr,Uo=Function.prototype,Ls=Uo.call,Ju=Fo&&Uo.bind.bind(Ls,Ls),ke=Fo?Ju:function(i){return function(){return Ls.apply(i,arguments)}},jo=ke,Xu=jo({}.toString),Zu=jo("".slice),fi=function(i){return Zu(Xu(i),8,-1)},ec=ke,tc=$e,ic=fi,Or=Object,rc=ec("".split),sc=tc(function(){return!Or("z").propertyIsEnumerable(0)})?function(i){return ic(i)=="String"?rc(i,""):Or(i)}:Or,pi=function(i){return i==null},ac=pi,nc=TypeError,sa=function(i){if(ac(i))throw nc("Can't call method on "+i);return i},oc=sc,lc=sa,mi=function(i){return oc(lc(i))},qt={},Ii=function(i){return i&&i.Math==Math&&i},ne=Ii(typeof globalThis=="object"&&globalThis)||Ii(typeof window=="object"&&window)||Ii(typeof self=="object"&&self)||Ii(typeof Nr=="object"&&Nr)||function(){return this}()||Nr||Function("return this")(),Ds=typeof document=="object"&&document.all,uc=typeof Ds=="undefined"&&Ds!==void 0,Ho={all:Ds,IS_HTMLDDA:uc},Go=Ho,cc=Go.all,ie=Go.IS_HTMLDDA?function(i){return typeof i=="function"||i===cc}:function(i){return typeof i=="function"},dc=ne,hc=ie,Wa=dc.WeakMap,fc=hc(Wa)&&/native code/.test(String(Wa)),za=ie,Yo=Ho,pc=Yo.all,Ye=Yo.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:za(i)||i===pc}:function(i){return typeof i=="object"?i!==null:za(i)},mc=$e,et=!mc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),mt={},vc=ne,Qa=Ye,xs=vc.document,bc=Qa(xs)&&Qa(xs.createElement),aa=function(i){return bc?xs.createElement(i):{}},Sc=et,gc=$e,yc=aa,qo=!Sc&&!gc(function(){return Object.defineProperty(yc("div"),"a",{get:function(){return 7}}).a!=7}),Tc=et,Ec=$e,Wo=Tc&&Ec(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),$c=Ye,kc=String,Pc=TypeError,qe=function(i){if($c(i))return i;throw Pc(kc(i)+" is not an object")},Ac=cr,_i=Function.prototype.call,ve=Ac?_i.bind(_i):function(){return _i.apply(_i,arguments)},na={},Mr=na,Br=ne,wc=ie,Ka=function(i){return wc(i)?i:void 0},vt=function(i,e){return arguments.length<2?Ka(Mr[i])||Ka(Br[i]):Mr[i]&&Mr[i][e]||Br[i]&&Br[i][e]},Cc=ke,dr=Cc({}.isPrototypeOf),hr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zo=ne,Vr=hr,Ja=zo.process,Xa=zo.Deno,Za=Ja&&Ja.versions||Xa&&Xa.version,en=Za&&Za.v8,we,er;en&&(we=en.split("."),er=we[0]>0&&we[0]<4?1:+(we[0]+we[1]));!er&&Vr&&(we=Vr.match(/Edge\/(\d+)/),(!we||we[1]>=74)&&(we=Vr.match(/Chrome\/(\d+)/),we&&(er=+we[1])));var Qo=er,tn=Qo,Ic=$e,_c=ne,Rc=_c.String,Ko=!!Object.getOwnPropertySymbols&&!Ic(function(){var i=Symbol();return!Rc(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&tn&&tn<41}),Lc=Ko,Jo=Lc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Dc=vt,xc=ie,Nc=dr,Oc=Jo,Mc=Object,Xo=Oc?function(i){return typeof i=="symbol"}:function(i){var e=Dc("Symbol");return xc(e)&&Nc(e.prototype,Mc(i))},Bc=String,fr=function(i){try{return Bc(i)}catch(e){return"Object"}},Vc=ie,Fc=fr,Uc=TypeError,bt=function(i){if(Vc(i))return i;throw Uc(Fc(i)+" is not a function")},jc=bt,Hc=pi,pr=function(i,e){var t=i[e];return Hc(t)?void 0:jc(t)},Fr=ve,Ur=ie,jr=Ye,Gc=TypeError,Yc=function(i,e){var t,r;if(e==="string"&&Ur(t=i.toString)&&!jr(r=Fr(t,i))||Ur(t=i.valueOf)&&!jr(r=Fr(t,i))||e!=="string"&&Ur(t=i.toString)&&!jr(r=Fr(t,i)))return r;throw Gc("Can't convert object to primitive value")},Zo={exports:{}},qc=!0,rn=ne,Wc=Object.defineProperty,zc=function(i,e){try{Wc(rn,i,{value:e,configurable:!0,writable:!0})}catch(t){rn[i]=e}return e},Qc=ne,Kc=zc,sn="__core-js_shared__",Jc=Qc[sn]||Kc(sn,{}),oa=Jc,an=oa;(Zo.exports=function(i,e){return an[i]||(an[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var el=Zo.exports,Xc=sa,Zc=Object,mr=function(i){return Zc(Xc(i))},ed=ke,td=mr,id=ed({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return id(td(e),t)},rd=ke,sd=0,ad=Math.random(),nd=rd(1 .toString),tl=function(i){return"Symbol("+(i===void 0?"":i)+")_"+nd(++sd+ad,36)},od=ne,ld=el,nn=Be,ud=tl,cd=Ko,dd=Jo,Bt=od.Symbol,Hr=ld("wks"),hd=dd?Bt.for||Bt:Bt&&Bt.withoutSetter||ud,de=function(i){return nn(Hr,i)||(Hr[i]=cd&&nn(Bt,i)?Bt[i]:hd("Symbol."+i)),Hr[i]},fd=ve,on=Ye,ln=Xo,pd=pr,md=Yc,vd=de,bd=TypeError,Sd=vd("toPrimitive"),gd=function(i,e){if(!on(i)||ln(i))return i;var t=pd(i,Sd),r;if(t){if(e===void 0&&(e="default"),r=fd(t,i,e),!on(r)||ln(r))return r;throw bd("Can't convert object to primitive value")}return e===void 0&&(e="number"),md(i,e)},yd=gd,Td=Xo,la=function(i){var e=yd(i,"string");return Td(e)?e:e+""},Ed=et,$d=qo,kd=Wo,Ri=qe,un=la,Pd=TypeError,Gr=Object.defineProperty,Ad=Object.getOwnPropertyDescriptor,Yr="enumerable",qr="configurable",Wr="writable";mt.f=Ed?kd?function(e,t,r){if(Ri(e),t=un(t),Ri(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Wr in r&&!r[Wr]){var s=Ad(e,t);s&&s[Wr]&&(e[t]=r.value,r={configurable:qr in r?r[qr]:s[qr],enumerable:Yr in r?r[Yr]:s[Yr],writable:!1})}return Gr(e,t,r)}:Gr:function(e,t,r){if(Ri(e),t=un(t),Ri(r),$d)try{return Gr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw Pd("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var vr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},wd=et,Cd=mt,Id=vr,vi=wd?function(i,e,t){return Cd.f(i,e,Id(1,t))}:function(i,e,t){return i[e]=t,i},_d=el,Rd=tl,cn=_d("keys"),ua=function(i){return cn[i]||(cn[i]=Rd(i))},ca={},Ld=fc,il=ne,Dd=Ye,xd=vi,zr=Be,Qr=oa,Nd=ua,Od=ca,dn="Object already initialized",Ns=il.TypeError,Md=il.WeakMap,tr,ui,ir,Bd=function(i){return ir(i)?ui(i):tr(i,{})},Vd=function(i){return function(e){var t;if(!Dd(e)||(t=ui(e)).type!==i)throw Ns("Incompatible receiver, "+i+" required");return t}};if(Ld||Qr.state){var Le=Qr.state||(Qr.state=new Md);Le.get=Le.get,Le.has=Le.has,Le.set=Le.set,tr=function(i,e){if(Le.has(i))throw Ns(dn);return e.facade=i,Le.set(i,e),e},ui=function(i){return Le.get(i)||{}},ir=function(i){return Le.has(i)}}else{var It=Nd("state");Od[It]=!0,tr=function(i,e){if(zr(i,It))throw Ns(dn);return e.facade=i,xd(i,It,e),e},ui=function(i){return zr(i,It)?i[It]:{}},ir=function(i){return zr(i,It)}}var rl={set:tr,get:ui,has:ir,enforce:Bd,getterFor:Vd},Fd=cr,sl=Function.prototype,hn=sl.apply,fn=sl.call,al=typeof Reflect=="object"&&Reflect.apply||(Fd?fn.bind(hn):function(){return fn.apply(hn,arguments)}),Ud=fi,jd=ke,nl=function(i){if(Ud(i)==="Function")return jd(i)},da={},ol={},ll={}.propertyIsEnumerable,ul=Object.getOwnPropertyDescriptor,Hd=ul&&!ll.call({1:2},1);ol.f=Hd?function(e){var t=ul(this,e);return!!t&&t.enumerable}:ll;var Gd=et,Yd=ve,qd=ol,Wd=vr,zd=mi,Qd=la,Kd=Be,Jd=qo,pn=Object.getOwnPropertyDescriptor;da.f=Gd?pn:function(e,t){if(e=zd(e),t=Qd(t),Jd)try{return pn(e,t)}catch(r){}if(Kd(e,t))return Wd(!Yd(qd.f,e,t),e[t])};var Xd=$e,Zd=ie,eh=/#|\.prototype\./,bi=function(i,e){var t=ih[th(i)];return t==sh?!0:t==rh?!1:Zd(e)?Xd(e):!!e},th=bi.normalize=function(i){return String(i).replace(eh,".").toLowerCase()},ih=bi.data={},rh=bi.NATIVE="N",sh=bi.POLYFILL="P",cl=bi,mn=nl,ah=bt,nh=cr,oh=mn(mn.bind),br=function(i,e){return ah(i),e===void 0?i:nh?oh(i,e):function(){return i.apply(e,arguments)}},Li=ne,lh=al,uh=nl,ch=ie,dh=da.f,hh=cl,_t=na,fh=br,Rt=vi,vn=Be,ph=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return lh(i,this,arguments)};return e.prototype=i.prototype,e},Ie=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?Li:s?Li[t]:(Li[t]||{}).prototype,l=r?_t:_t[t]||Rt(_t,t,{})[t],d=l.prototype,u,h,c,f,p,v,m,b,S;for(f in e)u=hh(r?f:t+(s?".":"#")+f,i.forced),h=!u&&o&&vn(o,f),v=l[f],h&&(i.dontCallGetSet?(S=dh(o,f),m=S&&S.value):m=o[f]),p=h&&m?m:e[f],!(h&&typeof v==typeof p)&&(i.bind&&h?b=fh(p,Li):i.wrap&&h?b=ph(p):n&&ch(p)?b=uh(p):b=p,(i.sham||p&&p.sham||v&&v.sham)&&Rt(b,"sham",!0),Rt(l,f,b),n&&(c=t+"Prototype",vn(_t,c)||Rt(_t,c,{}),Rt(_t[c],f,p),i.real&&d&&(u||!d[f])&&Rt(d,f,p)))},Os=et,mh=Be,dl=Function.prototype,vh=Os&&Object.getOwnPropertyDescriptor,ha=mh(dl,"name"),bh=ha&&function(){}.name==="something",Sh=ha&&(!Os||Os&&vh(dl,"name").configurable),gh={EXISTS:ha,PROPER:bh,CONFIGURABLE:Sh},hl={},yh=Math.ceil,Th=Math.floor,Eh=Math.trunc||function(e){var t=+e;return(t>0?Th:yh)(t)},$h=Eh,fa=function(i){var e=+i;return e!==e||e===0?0:$h(e)},kh=fa,Ph=Math.max,Ah=Math.min,wh=function(i,e){var t=kh(i);return t<0?Ph(t+e,0):Ah(t,e)},Ch=fa,Ih=Math.min,_h=function(i){return i>0?Ih(Ch(i),9007199254740991):0},Rh=_h,pa=function(i){return Rh(i.length)},Lh=mi,Dh=wh,xh=pa,bn=function(i){return function(e,t,r){var s=Lh(e),n=xh(s),o=Dh(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Nh={includes:bn(!0),indexOf:bn(!1)},Oh=ke,Kr=Be,Mh=mi,Bh=Nh.indexOf,Vh=ca,Sn=Oh([].push),Fh=function(i,e){var t=Mh(i),r=0,s=[],n;for(n in t)!Kr(Vh,n)&&Kr(t,n)&&Sn(s,n);for(;e.length>r;)Kr(t,n=e[r++])&&(~Bh(s,n)||Sn(s,n));return s},fl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Uh=Fh,jh=fl,Hh=Object.keys||function(e){return Uh(e,jh)},Gh=et,Yh=Wo,qh=mt,Wh=qe,zh=mi,Qh=Hh;hl.f=Gh&&!Yh?Object.defineProperties:function(e,t){Wh(e);for(var r=zh(t),s=Qh(t),n=s.length,o=0,l;n>o;)qh.f(e,l=s[o++],r[l]);return e};var Kh=vt,pl=Kh("document","documentElement"),Jh=qe,Xh=hl,gn=fl,Zh=ca,ef=pl,tf=aa,rf=ua,yn=">",Tn="<",Ms="prototype",Bs="script",ml=rf("IE_PROTO"),Jr=function(){},vl=function(i){return Tn+Bs+yn+i+Tn+"/"+Bs+yn},En=function(i){i.write(vl("")),i.close();var e=i.parentWindow.Object;return i=null,e},sf=function(){var i=tf("iframe"),e="java"+Bs+":",t;return i.style.display="none",ef.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(vl("document.F=Object")),t.close(),t.F},Di,Ki=function(){try{Di=new ActiveXObject("htmlfile")}catch(e){}Ki=typeof document!="undefined"?document.domain&&Di?En(Di):sf():En(Di);for(var i=gn.length;i--;)delete Ki[Ms][gn[i]];return Ki()};Zh[ml]=!0;var bl=Object.create||function(e,t){var r;return e!==null?(Jr[Ms]=Jh(e),r=new Jr,Jr[Ms]=null,r[ml]=e):r=Ki(),t===void 0?r:Xh.f(r,t)},af=$e,nf=!af(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),of=Be,lf=ie,uf=mr,cf=ua,df=nf,$n=cf("IE_PROTO"),Vs=Object,hf=Vs.prototype,Sl=df?Vs.getPrototypeOf:function(i){var e=uf(i);if(of(e,$n))return e[$n];var t=e.constructor;return lf(t)&&e instanceof t?t.prototype:e instanceof Vs?hf:null},ff=vi,ma=function(i,e,t,r){return r&&r.enumerable?i[e]=t:ff(i,e,t),i},pf=$e,mf=ie,vf=Ye,bf=bl,kn=Sl,Sf=ma,gf=de,Fs=gf("iterator"),gl=!1,He,Xr,Zr;[].keys&&(Zr=[].keys(),"next"in Zr?(Xr=kn(kn(Zr)),Xr!==Object.prototype&&(He=Xr)):gl=!0);var yf=!vf(He)||pf(function(){var i={};return He[Fs].call(i)!==i});yf?He={}:He=bf(He);mf(He[Fs])||Sf(He,Fs,function(){return this});var yl={IteratorPrototype:He,BUGGY_SAFARI_ITERATORS:gl},Tf=de,Ef=Tf("toStringTag"),Tl={};Tl[Ef]="z";var va=String(Tl)==="[object z]",$f=va,kf=ie,Ji=fi,Pf=de,Af=Pf("toStringTag"),wf=Object,Cf=Ji(function(){return arguments}())=="Arguments",If=function(i,e){try{return i[e]}catch(t){}},Si=$f?Ji:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=If(e=wf(i),Af))=="string"?t:Cf?Ji(e):(r=Ji(e))=="Object"&&kf(e.callee)?"Arguments":r},_f=va,Rf=Si,Lf=_f?{}.toString:function(){return"[object "+Rf(this)+"]"},Df=va,xf=mt.f,Nf=vi,Of=Be,Mf=Lf,Bf=de,Pn=Bf("toStringTag"),ba=function(i,e,t,r){if(i){var s=t?i:i.prototype;Of(s,Pn)||xf(s,Pn,{configurable:!0,value:e}),r&&!Df&&Nf(s,"toString",Mf)}},Vf=yl.IteratorPrototype,Ff=bl,Uf=vr,jf=ba,Hf=qt,Gf=function(){return this},Yf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=Ff(Vf,{next:Uf(+!r,t)}),jf(i,s,!1,!0),Hf[s]=Gf,i},qf=Ie,Wf=ve,El=gh,zf=Yf,Qf=Sl,Kf=ba,An=ma,Jf=de,wn=qt,$l=yl,Xf=El.PROPER;El.CONFIGURABLE;$l.IteratorPrototype;var xi=$l.BUGGY_SAFARI_ITERATORS,es=Jf("iterator"),Cn="keys",Ni="values",In="entries",Zf=function(){return this},ep=function(i,e,t,r,s,n,o){zf(t,e,r);var l=function(S){if(S===s&&f)return f;if(!xi&&S in h)return h[S];switch(S){case Cn:return function(){return new t(this,S)};case Ni:return function(){return new t(this,S)};case In:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,h=i.prototype,c=h[es]||h["@@iterator"]||s&&h[s],f=!xi&&c||l(s),p=e=="Array"&&h.entries||c,v,m,b;if(p&&(v=Qf(p.call(new i)),v!==Object.prototype&&v.next&&(Kf(v,d,!0,!0),wn[d]=Zf)),Xf&&s==Ni&&c&&c.name!==Ni&&(u=!0,f=function(){return Wf(c,this)}),s)if(m={values:l(Ni),keys:n?f:l(Cn),entries:l(In)},o)for(b in m)(xi||u||!(b in h))&&An(h,b,m[b]);else qf({target:e,proto:!0,forced:xi||u},m);return o&&h[es]!==f&&An(h,es,f,{name:s}),wn[e]=f,m},tp=function(i,e){return{value:i,done:e}},ip=mi,_n=qt,kl=rl;mt.f;var rp=ep,Oi=tp,Pl="Array Iterator",sp=kl.set,ap=kl.getterFor(Pl);rp(Array,"Array",function(i,e){sp(this,{type:Pl,target:ip(i),index:0,kind:e})},function(){var i=ap(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Oi(void 0,!0)):t=="keys"?Oi(r,!1):t=="values"?Oi(e[r],!1):Oi([r,e[r]],!1)},"values");_n.Arguments=_n.Array;var np=de,op=qt,lp=np("iterator"),up=Array.prototype,cp=function(i){return i!==void 0&&(op.Array===i||up[lp]===i)},dp=Si,Rn=pr,hp=pi,fp=qt,pp=de,mp=pp("iterator"),Al=function(i){if(!hp(i))return Rn(i,mp)||Rn(i,"@@iterator")||fp[dp(i)]},vp=ve,bp=bt,Sp=qe,gp=fr,yp=Al,Tp=TypeError,Ep=function(i,e){var t=arguments.length<2?yp(i):e;if(bp(t))return Sp(vp(t,i));throw Tp(gp(i)+" is not iterable")},$p=ve,Ln=qe,kp=pr,Pp=function(i,e,t){var r,s;Ln(i);try{if(r=kp(i,"return"),!r){if(e==="throw")throw t;return t}r=$p(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return Ln(r),t},Ap=br,wp=ve,Cp=qe,Ip=fr,_p=cp,Rp=pa,Dn=dr,Lp=Ep,Dp=Al,xn=Pp,xp=TypeError,Xi=function(i,e){this.stopped=i,this.result=e},Nn=Xi.prototype,Sa=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Ap(e,r),u,h,c,f,p,v,m,b=function(y){return u&&xn(u,"normal",y),new Xi(!0,y)},S=function(y){return s?(Cp(y),l?d(y[0],y[1],b):d(y[0],y[1])):l?d(y,b):d(y)};if(n)u=i.iterator;else if(o)u=i;else{if(h=Dp(i),!h)throw xp(Ip(i)+" is not iterable");if(_p(h)){for(c=0,f=Rp(i);f>c;c++)if(p=S(i[c]),p&&Dn(Nn,p))return p;return new Xi(!1)}u=Lp(i,h)}for(v=n?i.next:u.next;!(m=wp(v,u)).done;){try{p=S(m.value)}catch(y){xn(u,"throw",y)}if(typeof p=="object"&&p&&Dn(Nn,p))return p}return new Xi(!1)},Np=la,Op=mt,Mp=vr,Bp=function(i,e,t){var r=Np(e);r in i?Op.f(i,r,Mp(0,t)):i[r]=t},Vp=Ie,Fp=Sa,Up=Bp;Vp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Fp(e,function(r,s){Up(t,r,s)},{AS_ENTRIES:!0}),t}});var jp=na,Hp=jp.Object.fromEntries,Gp={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},Yp=Gp,qp=ne,Wp=Si,zp=vi,On=qt,Qp=de,Mn=Qp("toStringTag");for(var ts in Yp){var Bn=qp[ts],is=Bn&&Bn.prototype;is&&Wp(is)!==Mn&&zp(is,Mn,ts),On[ts]=On.Array}var Kp=Hp,Jp=Kp,Xp=Jp,Zp=Xp,rr=ur(Zp),em=fi,Sr=typeof process!="undefined"&&em(process)=="process",tm=mt,im=function(i,e,t){return tm.f(i,e,t)},rm=vt,sm=im,am=de,nm=et,Vn=am("species"),om=function(i){var e=rm(i);nm&&e&&!e[Vn]&&sm(e,Vn,{configurable:!0,get:function(){return this}})},lm=dr,um=TypeError,cm=function(i,e){if(lm(e,i))return i;throw um("Incorrect invocation")},dm=ke,hm=ie,Us=oa,fm=dm(Function.toString);hm(Us.inspectSource)||(Us.inspectSource=function(i){return fm(i)});var wl=Us.inspectSource,pm=ke,mm=$e,Cl=ie,vm=Si,bm=vt,Sm=wl,Il=function(){},gm=[],_l=bm("Reflect","construct"),ga=/^\s*(?:class|function)\b/,ym=pm(ga.exec),Tm=!ga.exec(Il),ii=function(e){if(!Cl(e))return!1;try{return _l(Il,gm,e),!0}catch(t){return!1}},Rl=function(e){if(!Cl(e))return!1;switch(vm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Tm||!!ym(ga,Sm(e))}catch(t){return!0}};Rl.sham=!0;var Em=!_l||mm(function(){var i;return ii(ii.call)||!ii(Object)||!ii(function(){i=!0})||i})?Rl:ii,$m=Em,km=fr,Pm=TypeError,Am=function(i){if($m(i))return i;throw Pm(km(i)+" is not a constructor")},Fn=qe,wm=Am,Cm=pi,Im=de,_m=Im("species"),Ll=function(i,e){var t=Fn(i).constructor,r;return t===void 0||Cm(r=Fn(t)[_m])?e:wm(r)},Rm=ke,Lm=Rm([].slice),Dm=TypeError,xm=function(i,e){if(i<e)throw Dm("Not enough arguments");return i},Nm=hr,Dl=/(?:ipad|iphone|ipod).*applewebkit/i.test(Nm),me=ne,Om=al,Mm=br,Un=ie,Bm=Be,xl=$e,jn=pl,Vm=Lm,Hn=aa,Fm=xm,Um=Dl,jm=Sr,js=me.setImmediate,Hs=me.clearImmediate,Hm=me.process,rs=me.Dispatch,Gm=me.Function,Gn=me.MessageChannel,Ym=me.String,ss=0,ai={},Yn="onreadystatechange",ci,ot,as,ns;xl(function(){ci=me.location});var ya=function(i){if(Bm(ai,i)){var e=ai[i];delete ai[i],e()}},os=function(i){return function(){ya(i)}},qn=function(i){ya(i.data)},Wn=function(i){me.postMessage(Ym(i),ci.protocol+"//"+ci.host)};(!js||!Hs)&&(js=function(e){Fm(arguments.length,1);var t=Un(e)?e:Gm(e),r=Vm(arguments,1);return ai[++ss]=function(){Om(t,void 0,r)},ot(ss),ss},Hs=function(e){delete ai[e]},jm?ot=function(i){Hm.nextTick(os(i))}:rs&&rs.now?ot=function(i){rs.now(os(i))}:Gn&&!Um?(as=new Gn,ns=as.port2,as.port1.onmessage=qn,ot=Mm(ns.postMessage,ns)):me.addEventListener&&Un(me.postMessage)&&!me.importScripts&&ci&&ci.protocol!=="file:"&&!xl(Wn)?(ot=Wn,me.addEventListener("message",qn,!1)):Yn in Hn("script")?ot=function(i){jn.appendChild(Hn("script"))[Yn]=function(){jn.removeChild(this),ya(i)}}:ot=function(i){setTimeout(os(i),0)});var Nl={set:js,clear:Hs},Ol=function(){this.head=null,this.tail=null};Ol.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Ml=Ol,qm=hr,Wm=/ipad|iphone|ipod/i.test(qm)&&typeof Pebble!="undefined",zm=hr,Qm=/web0s(?!.*chrome)/i.test(zm),ft=ne,zn=br,Km=da.f,ls=Nl.set,Jm=Ml,Xm=Dl,Zm=Wm,ev=Qm,us=Sr,Qn=ft.MutationObserver||ft.WebKitMutationObserver,Kn=ft.document,Jn=ft.process,Mi=ft.Promise,Xn=Km(ft,"queueMicrotask"),Gs=Xn&&Xn.value,Lt,cs,ds,Bi,Zn;if(!Gs){var Vi=new Jm,Fi=function(){var i,e;for(us&&(i=Jn.domain)&&i.exit();e=Vi.get();)try{e()}catch(t){throw Vi.head&&Lt(),t}i&&i.enter()};!Xm&&!us&&!ev&&Qn&&Kn?(cs=!0,ds=Kn.createTextNode(""),new Qn(Fi).observe(ds,{characterData:!0}),Lt=function(){ds.data=cs=!cs}):!Zm&&Mi&&Mi.resolve?(Bi=Mi.resolve(void 0),Bi.constructor=Mi,Zn=zn(Bi.then,Bi),Lt=function(){Zn(Fi)}):us?Lt=function(){Jn.nextTick(Fi)}:(ls=zn(ls,ft),Lt=function(){ls(Fi)}),Gs=function(i){Vi.head||Lt(),Vi.add(i)}}var tv=Gs,iv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Ta=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},rv=ne,Wt=rv.Promise,Bl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",sv=Bl,av=Sr,nv=!sv&&!av&&typeof window=="object"&&typeof document=="object",ov=ne,ni=Wt,lv=ie,uv=cl,cv=wl,dv=de,hv=nv,fv=Bl,hs=Qo,eo=ni&&ni.prototype,pv=dv("species"),Ys=!1,Vl=lv(ov.PromiseRejectionEvent),mv=uv("Promise",function(){var i=cv(ni),e=i!==String(ni);if(!e&&hs===66||!(eo.catch&&eo.finally))return!0;if(!hs||hs<51||!/native code/.test(i)){var t=new ni(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[pv]=r,Ys=t.then(function(){})instanceof r,!Ys)return!0}return!e&&(hv||fv)&&!Vl}),gi={CONSTRUCTOR:mv,REJECTION_EVENT:Vl,SUBCLASSING:Ys},zt={},to=bt,vv=TypeError,bv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw vv("Bad Promise constructor");e=r,t=s}),this.resolve=to(e),this.reject=to(t)};zt.f=function(i){return new bv(i)};var Sv=Ie,sr=Sr,Ze=ne,yi=ve,gv=ma,yv=ba,Tv=om,Ev=bt,qs=ie,$v=Ye,kv=cm,Pv=Ll,Fl=Nl.set,Ea=tv,Av=iv,wv=Ta,Cv=Ml,Ul=rl,Ws=Wt,$a=gi,jl=zt,gr="Promise",Hl=$a.CONSTRUCTOR,Iv=$a.REJECTION_EVENT;$a.SUBCLASSING;var fs=Ul.getterFor(gr),_v=Ul.set,Rv=Ws&&Ws.prototype,Vt=Ws,ps=Rv,Gl=Ze.TypeError,zs=Ze.document,ka=Ze.process,Qs=jl.f,Lv=Qs,Dv=!!(zs&&zs.createEvent&&Ze.dispatchEvent),Yl="unhandledrejection",xv="rejectionhandled",io=0,ql=1,Nv=2,Pa=1,Wl=2,Ui,ro,Ov,zl=function(i){var e;return $v(i)&&qs(e=i.then)?e:!1},Ql=function(i,e){var t=e.value,r=e.state==ql,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,h;try{s?(r||(e.rejection===Wl&&Bv(e),e.rejection=Pa),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),h=!0)),d===i.promise?o(Gl("Promise-chain cycle")):(u=zl(d))?yi(u,d,n,o):n(d)):o(t)}catch(c){l&&!h&&l.exit(),o(c)}},Kl=function(i,e){i.notified||(i.notified=!0,Ea(function(){for(var t=i.reactions,r;r=t.get();)Ql(r,i);i.notified=!1,e&&!i.rejection&&Mv(i)}))},Jl=function(i,e,t){var r,s;Dv?(r=zs.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Ze.dispatchEvent(r)):r={promise:e,reason:t},!Iv&&(s=Ze["on"+i])?s(r):i===Yl&&Av("Unhandled promise rejection",t)},Mv=function(i){yi(Fl,Ze,function(){var e=i.facade,t=i.value,r=so(i),s;if(r&&(s=wv(function(){sr?ka.emit("unhandledRejection",t,e):Jl(Yl,e,t)}),i.rejection=sr||so(i)?Wl:Pa,s.error))throw s.value})},so=function(i){return i.rejection!==Pa&&!i.parent},Bv=function(i){yi(Fl,Ze,function(){var e=i.facade;sr?ka.emit("rejectionHandled",e):Jl(xv,e,i.value)})},Ft=function(i,e,t){return function(r){i(e,r,t)}},jt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Nv,Kl(i,!0))},Ks=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Gl("Promise can't be resolved itself");var r=zl(e);r?Ea(function(){var s={done:!1};try{yi(r,e,Ft(Ks,s,i),Ft(jt,s,i))}catch(n){jt(s,n,i)}}):(i.value=e,i.state=ql,Kl(i,!1))}catch(s){jt({done:!1},s,i)}}};Hl&&(Vt=function(e){kv(this,ps),Ev(e),yi(Ui,this);var t=fs(this);try{e(Ft(Ks,t),Ft(jt,t))}catch(r){jt(t,r)}},ps=Vt.prototype,Ui=function(e){_v(this,{type:gr,done:!1,notified:!1,parent:!1,reactions:new Cv,rejection:!1,state:io,value:void 0})},Ui.prototype=gv(ps,"then",function(e,t){var r=fs(this),s=Qs(Pv(this,Vt));return r.parent=!0,s.ok=qs(e)?e:!0,s.fail=qs(t)&&t,s.domain=sr?ka.domain:void 0,r.state==io?r.reactions.add(s):Ea(function(){Ql(s,r)}),s.promise}),ro=function(){var i=new Ui,e=fs(i);this.promise=i,this.resolve=Ft(Ks,e),this.reject=Ft(jt,e)},jl.f=Qs=function(i){return i===Vt||i===Ov?new ro(i):Lv(i)});Sv({global:!0,constructor:!0,wrap:!0,forced:Hl},{Promise:Vt});yv(Vt,gr,!1,!0);Tv(gr);var Vv=de,Xl=Vv("iterator"),Zl=!1;try{var Fv=0,ao={next:function(){return{done:!!Fv++}},return:function(){Zl=!0}};ao[Xl]=function(){return this},Array.from(ao,function(){throw 2})}catch(i){}var Uv=function(i,e){if(!e&&!Zl)return!1;var t=!1;try{var r={};r[Xl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},jv=Wt,Hv=Uv,Gv=gi.CONSTRUCTOR,eu=Gv||!Hv(function(i){jv.all(i).then(void 0,function(){})}),Yv=Ie,qv=ve,Wv=bt,zv=zt,Qv=Ta,Kv=Sa,Jv=eu;Yv({target:"Promise",stat:!0,forced:Jv},{all:function(e){var t=this,r=zv.f(t),s=r.resolve,n=r.reject,o=Qv(function(){var l=Wv(t.resolve),d=[],u=0,h=1;Kv(e,function(c){var f=u++,p=!1;h++,qv(l,t,c).then(function(v){p||(p=!0,d[f]=v,--h||s(d))},n)}),--h||s(d)});return o.error&&n(o.value),r.promise}});var Xv=Ie,Zv=gi.CONSTRUCTOR,no=Wt;no&&no.prototype;Xv({target:"Promise",proto:!0,forced:Zv,real:!0},{catch:function(i){return this.then(void 0,i)}});var eb=Ie,tb=ve,ib=bt,rb=zt,sb=Ta,ab=Sa,nb=eu;eb({target:"Promise",stat:!0,forced:nb},{race:function(e){var t=this,r=rb.f(t),s=r.reject,n=sb(function(){var o=ib(t.resolve);ab(e,function(l){tb(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var ob=Ie,lb=ve,ub=zt,cb=gi.CONSTRUCTOR;ob({target:"Promise",stat:!0,forced:cb},{reject:function(e){var t=ub.f(this);return lb(t.reject,void 0,e),t.promise}});var db=qe,hb=Ye,fb=zt,tu=function(i,e){if(db(i),hb(e)&&e.constructor===i)return e;var t=fb.f(i),r=t.resolve;return r(e),t.promise},pb=Ie,mb=vt,vb=qc,bb=Wt,Sb=gi.CONSTRUCTOR,gb=tu,yb=mb("Promise"),Tb=!Sb;pb({target:"Promise",stat:!0,forced:vb},{resolve:function(e){return gb(Tb&&this===yb?bb:this,e)}});var Eb=Ie,Js=Wt,$b=$e,kb=vt,Pb=ie,Ab=Ll,oo=tu,wb=Js&&Js.prototype,Cb=!!Js&&$b(function(){wb.finally.call({then:function(){}},function(){})});Eb({target:"Promise",proto:!0,real:!0,forced:Cb},{finally:function(i){var e=Ab(this,kb("Promise")),t=Pb(i);return this.then(t?function(r){return oo(e,i()).then(function(){return r})}:i,t?function(r){return oo(e,i()).then(function(){throw r})}:i)}});var Ib=vt,Aa=Ib,_b=Aa,Rb=_b("Promise","finally"),Lb=Rb,Db=Lb,xb=Db,Nb=xb,wa=ur(Nb),re;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(re||(re={}));var Ce=(i,e=0,t=re.OFFSET_P)=>{switch(t){case re.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case re.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case re.DASH_CMAF_OFFSET_P:{const r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:a.assertNever(t)}return i};const lo=(i,e)=>{var t;switch(e){case re.OFFSET_P:return NaN;case re.PLAYBACK_SHIFT:{const r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case re.DASH_CMAF_OFFSET_P:{const r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var w=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};class Z{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Ob=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const Mb=5,Bb=5,Vb=500,uo=7e3;class Fb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new Z(L.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ob(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Vb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===N.Applying||Math.abs(l-n)>Mb)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Bb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(L.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:N.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const h=r[e];a.assertNonNullable(h);const c=a.getHighestQuality(Object.keys(h));a.assertNonNullable(c);const f=h[c];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const h=r[e];a.assertNonNullable(h),s=h.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const h=r[e];a.assertNonNullable(h),s=h.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const h=r[e];a.assertNonNullable(h),s=h.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const h=r[e];a.assertNonNullable(h),s=Ce(h.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const h="Unsupported format for Chromecast",c=new Error(h);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:h,thrown:c}),c}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===N.Applying||r.state===N.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(uo).subscribe(()=>n(`timeout(${uo})`)))});wa(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Ca=i=>{i.removeAttribute("src"),i.load()},Ub=i=>{try{i.pause(),i.playbackRate=0,Ca(i),i.remove()}catch(e){console.error(e)}};class jb{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Xs=window.WeakMap?new WeakMap:new jb,St=i=>{let e=i.querySelector("video");const t=!!e;return e?Ca(e):(e=document.createElement("video"),i.appendChild(e)),Xs.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},gt=i=>{const e=Xs.get(i);Xs.delete(i),e?Ca(i):Ub(i)},Ue=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(h=>{const c=i.getState();r(h,c)&&i.setState(h)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(h=>{t(h.to),d&&i.setState(h.to)},n)),u},Ti=(i,e,t)=>Ue(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),yt=(i,e,t,r)=>Ue(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),Qt=(i,e,t,r)=>Ue(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Hb=i=>["__",i.language,i.label].join("|"),Gb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class tt{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ue(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{a.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ue(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ue(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ue(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,h,c,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((c=(h=l.target)===null||h===void 0?void 0:h.cues)!==null&&c!==void 0?c:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(tt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,r;const{language:s,label:n}=e,o=e.id?e.id:Hb(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:s,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:s,label:n,url:(r=this.internalTracks.get(o))===null||r===void 0?void 0:r.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:r,language:s,isAuto:n})=>!this.internalTracks.has(r)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(s=>s.id===r)).forEach(([,r])=>this.detach(r))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Gb(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class Ia{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,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const iu=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},co=i=>{const e=iu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Yb=i=>{const e=iu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},qb=3;var Wb=(i,e,t=qb)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const Tt=i=>{const e=T=>a.fromEvent(i,T).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(T=>a.fromEvent(i,T))).pipe(a.map(T=>T.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Wb(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var T;const E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(T=i.error)!==null&&T!==void 0?T:void 0}})),h=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),c=new a.Subject,f=.3;let p;h.subscribe(T=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(T)&&p>=i.duration-f&&T<=f&&c.next(p),p=T});const v=a.fromEvent(i,"enterpictureinpicture"),m=a.fromEvent(i,"leavepictureinpicture"),b=new a.ValueSubject(Yb(i));v.subscribe(()=>b.next(!0)),m.subscribe(()=>b.next(!1));const S=new a.ValueSubject(co(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>co(i))).subscribe(S),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,playbackRateState$:d,inPiP$:b,inFullscreen$:S}};var yr=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}},zb=Ie,Qb=mr,Kb=pa,Jb=fa;zb({target:"Array",proto:!0},{at:function(e){var t=Qb(this),r=Kb(t),s=Jb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Xb=Aa,Zb=Xb("Array","at"),eS=Zb,tS=eS,iS=tS,rS=iS,Fe=ur(rS);let _a=!1,je={};const sS=i=>{_a=i},aS=()=>{je={}},nS=i=>{i(je)},ji=(i,e)=>{var t;_a&&(je.meta=(t=je.meta)!==null&&t!==void 0?t:{},je.meta[i]=e)};class xe{constructor(e){this.name=e}next(e){var t,r;if(!_a)return;je.series=(t=je.series)!==null&&t!==void 0?t:{};const s=(r=je.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),je.series[this.name]=s}}var dt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(dt||(dt={}));const oS=new xe("best_bitrate"),lS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class uS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const cS='Assertion "ABR Tracks is empty array" failed',Tr=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:h,abrLogger:c})=>{var f,p,v,m,b;a.assertNotEmptyArray(i,cS);const S=r.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*r.containerSizeFactor,height:e.height*S*r.containerSizeFactor},T=y&&a.videoSizeToQuality(y),E=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,$=i.filter(_=>!a.isInvariantQuality(_.quality)).sort((_,P)=>a.isHigher(_.quality,P.quality)?-1:1),O=(p=Fe($,-1))===null||p===void 0?void 0:p.quality,M=(v=Fe($,0))===null||v===void 0?void 0:v.quality,F=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&a.isLower(s.max,s.min)||a.isNonNullable(s.min)&&M&&a.isHigher(s.min,M)||a.isNonNullable(s.max)&&O&&a.isLower(s.max,O),x=E*lS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),U={},I=$.filter(_=>(T?a.isLower(_.quality,T):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(_.bitrate)?t-n>=_.bitrate*x:!0)?r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&a.isHigher(_.quality,d.quality)?(U[_.quality]=dt.Buffer,!1):!!h&&a.isHigherOrEqual(_.quality,h)?(U[_.quality]=dt.DroppedFramesLimit,!1):F||(a.isNullable(s.max)||a.isLowerOrEqual(_.quality,s.max))&&(a.isNullable(s.min)||a.isHigherOrEqual(_.quality,s.min))?!0:(U[_.quality]=dt.FitsQualityLimits,!1):(U[_.quality]=dt.FitsThroughput,!1):(U[_.quality]=dt.FitsContainer,!1))[0];I&&I.bitrate&&oS.next(I.bitrate);const A=(m=I!=null?I:$[Math.ceil(($.length-1)/2)])!==null&&m!==void 0?m:i[0];A.quality!==((b=u==null?void 0:u.last)===null||b===void 0?void 0:b.quality)&&c({message:`
6
+ "use strict";var bb=Object.create;var Nr=Object.defineProperty,gb=Object.defineProperties,vb=Object.getOwnPropertyDescriptor,Sb=Object.getOwnPropertyDescriptors,yb=Object.getOwnPropertyNames,Su=Object.getOwnPropertySymbols,Tb=Object.getPrototypeOf,Tu=Object.prototype.hasOwnProperty,Ib=Object.prototype.propertyIsEnumerable;var Xe=Math.pow,yu=(i,e,t)=>e in i?Nr(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,M=(i,e)=>{for(var t in e||(e={}))Tu.call(e,t)&&yu(i,t,e[t]);if(Su)for(var t of Su(e))Ib.call(e,t)&&yu(i,t,e[t]);return i},z=(i,e)=>gb(i,Sb(e));var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Eb=(i,e)=>{for(var t in e)Nr(i,t,{get:e[t],enumerable:!0})},Iu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of yb(e))!Tu.call(i,a)&&a!==t&&Nr(i,a,{get:()=>e[a],enumerable:!(r=vb(e,a))||r.enumerable});return i};var He=(i,e,t)=>(t=i!=null?bb(Tb(i)):{},Iu(e||!i||!i.__esModule?Nr(t,"default",{value:i,enumerable:!0}):t,i)),xb=i=>Iu(Nr({},"__esModule",{value:!0}),i);var _=(i,e,t)=>new Promise((r,a)=>{var s=u=>{try{o(t.next(u))}catch(l){a(l)}},n=u=>{try{o(t.throw(u))}catch(l){a(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(i,e)).next())}),Pb=function(i,e){this[0]=i,this[1]=e},pe=(i,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Pb,p=c.done;Promise.resolve(d?o[0]:o).then(f=>d?r(n==="return"?n:"next",o[1]?{done:f.done,value:f.value}:f,u,l):u({value:f,done:p})).catch(f=>r("throw",f,u,l))}catch(f){l(f)}},a=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(i,e),s[Symbol.asyncIterator]=()=>s,a("next"),a("throw"),a("return"),s};var Le=b((UP,xu)=>{"use strict";xu.exports=function(i){try{return!!i()}catch(e){return!0}}});var qr=b((HP,Pu)=>{"use strict";var kb=Le();Pu.exports=!kb(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var Ie=b((jP,Au)=>{"use strict";var wu=qr(),ku=Function.prototype,Bs=ku.call,Ab=wu&&ku.bind.bind(Bs,Bs);Au.exports=wu?Ab:function(i){return function(){return Bs.apply(i,arguments)}}});var dr=b((GP,Lu)=>{"use strict";var Ru=Ie(),Rb=Ru({}.toString),Lb=Ru("".slice);Lu.exports=function(i){return Lb(Rb(i),8,-1)}});var Cu=b((YP,$u)=>{"use strict";var $b=Ie(),Cb=Le(),Db=dr(),Vs=Object,Mb=$b("".split);$u.exports=Cb(function(){return!Vs("z").propertyIsEnumerable(0)})?function(i){return Db(i)=="String"?Mb(i,""):Vs(i)}:Vs});var pr=b((WP,Du)=>{"use strict";Du.exports=function(i){return i==null}});var da=b((QP,Mu)=>{"use strict";var Ob=pr(),Bb=TypeError;Mu.exports=function(i){if(Ob(i))throw Bb("Can't call method on "+i);return i}});var hr=b((zP,Ou)=>{"use strict";var Vb=Cu(),_b=da();Ou.exports=function(i){return Vb(_b(i))}});var _s=b((KP,Bu)=>{"use strict";Bu.exports=function(){}});var Ft=b((JP,Vu)=>{"use strict";Vu.exports={}});var he=b((_u,Nu)=>{"use strict";var pa=function(i){return i&&i.Math==Math&&i};Nu.exports=pa(typeof globalThis=="object"&&globalThis)||pa(typeof window=="object"&&window)||pa(typeof self=="object"&&self)||pa(typeof global=="object"&&global)||function(){return this}()||_u||Function("return this")()});var Fs=b((XP,Fu)=>{"use strict";var Ns=typeof document=="object"&&document.all,Nb=typeof Ns=="undefined"&&Ns!==void 0;Fu.exports={all:Ns,IS_HTMLDDA:Nb}});var se=b((ZP,Uu)=>{"use strict";var qu=Fs(),Fb=qu.all;Uu.exports=qu.IS_HTMLDDA?function(i){return typeof i=="function"||i===Fb}:function(i){return typeof i=="function"}});var Gu=b((ew,ju)=>{"use strict";var qb=he(),Ub=se(),Hu=qb.WeakMap;ju.exports=Ub(Hu)&&/native code/.test(String(Hu))});var Ze=b((tw,Qu)=>{"use strict";var Yu=se(),Wu=Fs(),Hb=Wu.all;Qu.exports=Wu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Yu(i)||i===Hb}:function(i){return typeof i=="object"?i!==null:Yu(i)}});var et=b((rw,zu)=>{"use strict";var jb=Le();zu.exports=!jb(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var ha=b((iw,Ju)=>{"use strict";var Gb=he(),Ku=Ze(),qs=Gb.document,Yb=Ku(qs)&&Ku(qs.createElement);Ju.exports=function(i){return Yb?qs.createElement(i):{}}});var Us=b((aw,Xu)=>{"use strict";var Wb=et(),Qb=Le(),zb=ha();Xu.exports=!Wb&&!Qb(function(){return Object.defineProperty(zb("div"),"a",{get:function(){return 7}}).a!=7})});var Hs=b((sw,Zu)=>{"use strict";var Kb=et(),Jb=Le();Zu.exports=Kb&&Jb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var je=b((nw,el)=>{"use strict";var Xb=Ze(),Zb=String,eg=TypeError;el.exports=function(i){if(Xb(i))return i;throw eg(Zb(i)+" is not an object")}});var Ee=b((ow,tl)=>{"use strict";var tg=qr(),fa=Function.prototype.call;tl.exports=tg?fa.bind(fa):function(){return fa.apply(fa,arguments)}});var ma=b((uw,rl)=>{"use strict";rl.exports={}});var ot=b((lw,al)=>{"use strict";var js=ma(),Gs=he(),rg=se(),il=function(i){return rg(i)?i:void 0};al.exports=function(i,e){return arguments.length<2?il(js[i])||il(Gs[i]):js[i]&&js[i][e]||Gs[i]&&Gs[i][e]}});var Ur=b((cw,sl)=>{"use strict";var ig=Ie();sl.exports=ig({}.isPrototypeOf)});var Hr=b((dw,nl)=>{"use strict";nl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var Ws=b((pw,pl)=>{"use strict";var dl=he(),Ys=Hr(),ol=dl.process,ul=dl.Deno,ll=ol&&ol.versions||ul&&ul.version,cl=ll&&ll.v8,Ge,ba;cl&&(Ge=cl.split("."),ba=Ge[0]>0&&Ge[0]<4?1:+(Ge[0]+Ge[1]));!ba&&Ys&&(Ge=Ys.match(/Edge\/(\d+)/),(!Ge||Ge[1]>=74)&&(Ge=Ys.match(/Chrome\/(\d+)/),Ge&&(ba=+Ge[1])));pl.exports=ba});var Qs=b((hw,fl)=>{"use strict";var hl=Ws(),ag=Le(),sg=he(),ng=sg.String;fl.exports=!!Object.getOwnPropertySymbols&&!ag(function(){var i=Symbol();return!ng(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&hl&&hl<41})});var zs=b((fw,ml)=>{"use strict";var og=Qs();ml.exports=og&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ks=b((mw,bl)=>{"use strict";var ug=ot(),lg=se(),cg=Ur(),dg=zs(),pg=Object;bl.exports=dg?function(i){return typeof i=="symbol"}:function(i){var e=ug("Symbol");return lg(e)&&cg(e.prototype,pg(i))}});var jr=b((bw,gl)=>{"use strict";var hg=String;gl.exports=function(i){try{return hg(i)}catch(e){return"Object"}}});var ut=b((gw,vl)=>{"use strict";var fg=se(),mg=jr(),bg=TypeError;vl.exports=function(i){if(fg(i))return i;throw bg(mg(i)+" is not a function")}});var Gr=b((vw,Sl)=>{"use strict";var gg=ut(),vg=pr();Sl.exports=function(i,e){var t=i[e];return vg(t)?void 0:gg(t)}});var Tl=b((Sw,yl)=>{"use strict";var Js=Ee(),Xs=se(),Zs=Ze(),Sg=TypeError;yl.exports=function(i,e){var t,r;if(e==="string"&&Xs(t=i.toString)&&!Zs(r=Js(t,i))||Xs(t=i.valueOf)&&!Zs(r=Js(t,i))||e!=="string"&&Xs(t=i.toString)&&!Zs(r=Js(t,i)))return r;throw Sg("Can't convert object to primitive value")}});var Ye=b((yw,Il)=>{"use strict";Il.exports=!0});var Pl=b((Tw,xl)=>{"use strict";var El=he(),yg=Object.defineProperty;xl.exports=function(i,e){try{yg(El,i,{value:e,configurable:!0,writable:!0})}catch(t){El[i]=e}return e}});var ga=b((Iw,kl)=>{"use strict";var Tg=he(),Ig=Pl(),wl="__core-js_shared__",Eg=Tg[wl]||Ig(wl,{});kl.exports=Eg});var en=b((Ew,Rl)=>{"use strict";var xg=Ye(),Al=ga();(Rl.exports=function(i,e){return Al[i]||(Al[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:xg?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Yr=b((xw,Ll)=>{"use strict";var Pg=da(),wg=Object;Ll.exports=function(i){return wg(Pg(i))}});var We=b((Pw,$l)=>{"use strict";var kg=Ie(),Ag=Yr(),Rg=kg({}.hasOwnProperty);$l.exports=Object.hasOwn||function(e,t){return Rg(Ag(e),t)}});var tn=b((ww,Cl)=>{"use strict";var Lg=Ie(),$g=0,Cg=Math.random(),Dg=Lg(1 .toString);Cl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Dg(++$g+Cg,36)}});var be=b((kw,Ml)=>{"use strict";var Mg=he(),Og=en(),Dl=We(),Bg=tn(),Vg=Qs(),_g=zs(),fr=Mg.Symbol,rn=Og("wks"),Ng=_g?fr.for||fr:fr&&fr.withoutSetter||Bg;Ml.exports=function(i){return Dl(rn,i)||(rn[i]=Vg&&Dl(fr,i)?fr[i]:Ng("Symbol."+i)),rn[i]}});var _l=b((Aw,Vl)=>{"use strict";var Fg=Ee(),Ol=Ze(),Bl=Ks(),qg=Gr(),Ug=Tl(),Hg=be(),jg=TypeError,Gg=Hg("toPrimitive");Vl.exports=function(i,e){if(!Ol(i)||Bl(i))return i;var t=qg(i,Gg),r;if(t){if(e===void 0&&(e="default"),r=Fg(t,i,e),!Ol(r)||Bl(r))return r;throw jg("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ug(i,e)}});var va=b((Rw,Nl)=>{"use strict";var Yg=_l(),Wg=Ks();Nl.exports=function(i){var e=Yg(i,"string");return Wg(e)?e:e+""}});var qt=b(ql=>{"use strict";var Qg=et(),zg=Us(),Kg=Hs(),Sa=je(),Fl=va(),Jg=TypeError,an=Object.defineProperty,Xg=Object.getOwnPropertyDescriptor,sn="enumerable",nn="configurable",on="writable";ql.f=Qg?Kg?function(e,t,r){if(Sa(e),t=Fl(t),Sa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&on in r&&!r[on]){var a=Xg(e,t);a&&a[on]&&(e[t]=r.value,r={configurable:nn in r?r[nn]:a[nn],enumerable:sn in r?r[sn]:a[sn],writable:!1})}return an(e,t,r)}:an:function(e,t,r){if(Sa(e),t=Fl(t),Sa(r),zg)try{return an(e,t,r)}catch(a){}if("get"in r||"set"in r)throw Jg("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Wr=b(($w,Ul)=>{"use strict";Ul.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Ut=b((Cw,Hl)=>{"use strict";var Zg=et(),ev=qt(),tv=Wr();Hl.exports=Zg?function(i,e,t){return ev.f(i,e,tv(1,t))}:function(i,e,t){return i[e]=t,i}});var ya=b((Dw,Gl)=>{"use strict";var rv=en(),iv=tn(),jl=rv("keys");Gl.exports=function(i){return jl[i]||(jl[i]=iv(i))}});var Ta=b((Mw,Yl)=>{"use strict";Yl.exports={}});var dn=b((Ow,zl)=>{"use strict";var av=Gu(),Ql=he(),sv=Ze(),nv=Ut(),un=We(),ln=ga(),ov=ya(),uv=Ta(),Wl="Object already initialized",cn=Ql.TypeError,lv=Ql.WeakMap,Ia,Qr,Ea,cv=function(i){return Ea(i)?Qr(i):Ia(i,{})},dv=function(i){return function(e){var t;if(!sv(e)||(t=Qr(e)).type!==i)throw cn("Incompatible receiver, "+i+" required");return t}};av||ln.state?(Qe=ln.state||(ln.state=new lv),Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Ia=function(i,e){if(Qe.has(i))throw cn(Wl);return e.facade=i,Qe.set(i,e),e},Qr=function(i){return Qe.get(i)||{}},Ea=function(i){return Qe.has(i)}):(Ht=ov("state"),uv[Ht]=!0,Ia=function(i,e){if(un(i,Ht))throw cn(Wl);return e.facade=i,nv(i,Ht,e),e},Qr=function(i){return un(i,Ht)?i[Ht]:{}},Ea=function(i){return un(i,Ht)});var Qe,Ht;zl.exports={set:Ia,get:Qr,has:Ea,enforce:cv,getterFor:dv}});var pn=b((Bw,Zl)=>{"use strict";var pv=qr(),Xl=Function.prototype,Kl=Xl.apply,Jl=Xl.call;Zl.exports=typeof Reflect=="object"&&Reflect.apply||(pv?Jl.bind(Kl):function(){return Jl.apply(Kl,arguments)})});var hn=b((Vw,ec)=>{"use strict";var hv=dr(),fv=Ie();ec.exports=function(i){if(hv(i)==="Function")return fv(i)}});var ac=b(ic=>{"use strict";var tc={}.propertyIsEnumerable,rc=Object.getOwnPropertyDescriptor,mv=rc&&!tc.call({1:2},1);ic.f=mv?function(e){var t=rc(this,e);return!!t&&t.enumerable}:tc});var fn=b(nc=>{"use strict";var bv=et(),gv=Ee(),vv=ac(),Sv=Wr(),yv=hr(),Tv=va(),Iv=We(),Ev=Us(),sc=Object.getOwnPropertyDescriptor;nc.f=bv?sc:function(e,t){if(e=yv(e),t=Tv(t),Ev)try{return sc(e,t)}catch(r){}if(Iv(e,t))return Sv(!gv(vv.f,e,t),e[t])}});var mn=b((Fw,oc)=>{"use strict";var xv=Le(),Pv=se(),wv=/#|\.prototype\./,zr=function(i,e){var t=Av[kv(i)];return t==Lv?!0:t==Rv?!1:Pv(e)?xv(e):!!e},kv=zr.normalize=function(i){return String(i).replace(wv,".").toLowerCase()},Av=zr.data={},Rv=zr.NATIVE="N",Lv=zr.POLYFILL="P";oc.exports=zr});var Kr=b((qw,lc)=>{"use strict";var uc=hn(),$v=ut(),Cv=qr(),Dv=uc(uc.bind);lc.exports=function(i,e){return $v(i),e===void 0?i:Cv?Dv(i,e):function(){return i.apply(e,arguments)}}});var Oe=b((Uw,dc)=>{"use strict";var xa=he(),Mv=pn(),Ov=hn(),Bv=se(),Vv=fn().f,_v=mn(),mr=ma(),Nv=Kr(),br=Ut(),cc=We(),Fv=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return Mv(i,this,arguments)};return e.prototype=i.prototype,e};dc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?xa:a?xa[t]:(xa[t]||{}).prototype,o=r?mr:mr[t]||br(mr,t,{})[t],u=o.prototype,l,c,d,p,f,m,g,S,y;for(p in e)l=_v(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&cc(n,p),m=o[p],c&&(i.dontCallGetSet?(y=Vv(n,p),g=y&&y.value):g=n[p]),f=c&&g?g:e[p],!(c&&typeof m==typeof f)&&(i.bind&&c?S=Nv(f,xa):i.wrap&&c?S=Fv(f):s&&Bv(f)?S=Ov(f):S=f,(i.sham||f&&f.sham||m&&m.sham)&&br(S,"sham",!0),br(o,p,S),s&&(d=t+"Prototype",cc(mr,d)||br(mr,d,{}),br(mr[d],p,f),i.real&&u&&(l||!u[p])&&br(u,p,f)))}});var fc=b((Hw,hc)=>{"use strict";var bn=et(),qv=We(),pc=Function.prototype,Uv=bn&&Object.getOwnPropertyDescriptor,gn=qv(pc,"name"),Hv=gn&&function(){}.name==="something",jv=gn&&(!bn||bn&&Uv(pc,"name").configurable);hc.exports={EXISTS:gn,PROPER:Hv,CONFIGURABLE:jv}});var bc=b((jw,mc)=>{"use strict";var Gv=Math.ceil,Yv=Math.floor;mc.exports=Math.trunc||function(e){var t=+e;return(t>0?Yv:Gv)(t)}});var Pa=b((Gw,gc)=>{"use strict";var Wv=bc();gc.exports=function(i){var e=+i;return e!==e||e===0?0:Wv(e)}});var Sc=b((Yw,vc)=>{"use strict";var Qv=Pa(),zv=Math.max,Kv=Math.min;vc.exports=function(i,e){var t=Qv(i);return t<0?zv(t+e,0):Kv(t,e)}});var Tc=b((Ww,yc)=>{"use strict";var Jv=Pa(),Xv=Math.min;yc.exports=function(i){return i>0?Xv(Jv(i),9007199254740991):0}});var wa=b((Qw,Ic)=>{"use strict";var Zv=Tc();Ic.exports=function(i){return Zv(i.length)}});var Pc=b((zw,xc)=>{"use strict";var eS=hr(),tS=Sc(),rS=wa(),Ec=function(i){return function(e,t,r){var a=eS(e),s=rS(a),n=tS(r,s),o;if(i&&t!=t){for(;s>n;)if(o=a[n++],o!=o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};xc.exports={includes:Ec(!0),indexOf:Ec(!1)}});var Ac=b((Kw,kc)=>{"use strict";var iS=Ie(),vn=We(),aS=hr(),sS=Pc().indexOf,nS=Ta(),wc=iS([].push);kc.exports=function(i,e){var t=aS(i),r=0,a=[],s;for(s in t)!vn(nS,s)&&vn(t,s)&&wc(a,s);for(;e.length>r;)vn(t,s=e[r++])&&(~sS(a,s)||wc(a,s));return a}});var Sn=b((Jw,Rc)=>{"use strict";Rc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var $c=b((Xw,Lc)=>{"use strict";var oS=Ac(),uS=Sn();Lc.exports=Object.keys||function(e){return oS(e,uS)}});var Dc=b(Cc=>{"use strict";var lS=et(),cS=Hs(),dS=qt(),pS=je(),hS=hr(),fS=$c();Cc.f=lS&&!cS?Object.defineProperties:function(e,t){pS(e);for(var r=hS(t),a=fS(t),s=a.length,n=0,o;s>n;)dS.f(e,o=a[n++],r[o]);return e}});var yn=b((ek,Mc)=>{"use strict";var mS=ot();Mc.exports=mS("document","documentElement")});var xn=b((tk,qc)=>{"use strict";var bS=je(),gS=Dc(),Oc=Sn(),vS=Ta(),SS=yn(),yS=ha(),TS=ya(),Bc=">",Vc="<",In="prototype",En="script",Nc=TS("IE_PROTO"),Tn=function(){},Fc=function(i){return Vc+En+Bc+i+Vc+"/"+En+Bc},_c=function(i){i.write(Fc("")),i.close();var e=i.parentWindow.Object;return i=null,e},IS=function(){var i=yS("iframe"),e="java"+En+":",t;return i.style.display="none",SS.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Fc("document.F=Object")),t.close(),t.F},ka,Aa=function(){try{ka=new ActiveXObject("htmlfile")}catch(e){}Aa=typeof document!="undefined"?document.domain&&ka?_c(ka):IS():_c(ka);for(var i=Oc.length;i--;)delete Aa[In][Oc[i]];return Aa()};vS[Nc]=!0;qc.exports=Object.create||function(e,t){var r;return e!==null?(Tn[In]=bS(e),r=new Tn,Tn[In]=null,r[Nc]=e):r=Aa(),t===void 0?r:gS.f(r,t)}});var Hc=b((rk,Uc)=>{"use strict";var ES=Le();Uc.exports=!ES(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var wn=b((ik,Gc)=>{"use strict";var xS=We(),PS=se(),wS=Yr(),kS=ya(),AS=Hc(),jc=kS("IE_PROTO"),Pn=Object,RS=Pn.prototype;Gc.exports=AS?Pn.getPrototypeOf:function(i){var e=wS(i);if(xS(e,jc))return e[jc];var t=e.constructor;return PS(t)&&e instanceof t?t.prototype:e instanceof Pn?RS:null}});var gr=b((ak,Yc)=>{"use strict";var LS=Ut();Yc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:LS(i,e,t),i}});var Ln=b((sk,zc)=>{"use strict";var $S=Le(),CS=se(),DS=Ze(),MS=xn(),Wc=wn(),OS=gr(),BS=be(),VS=Ye(),Rn=BS("iterator"),Qc=!1,lt,kn,An;[].keys&&(An=[].keys(),"next"in An?(kn=Wc(Wc(An)),kn!==Object.prototype&&(lt=kn)):Qc=!0);var _S=!DS(lt)||$S(function(){var i={};return lt[Rn].call(i)!==i});_S?lt={}:VS&&(lt=MS(lt));CS(lt[Rn])||OS(lt,Rn,function(){return this});zc.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Qc}});var Ra=b((nk,Jc)=>{"use strict";var NS=be(),FS=NS("toStringTag"),Kc={};Kc[FS]="z";Jc.exports=String(Kc)==="[object z]"});var vr=b((ok,Xc)=>{"use strict";var qS=Ra(),US=se(),La=dr(),HS=be(),jS=HS("toStringTag"),GS=Object,YS=La(function(){return arguments}())=="Arguments",WS=function(i,e){try{return i[e]}catch(t){}};Xc.exports=qS?La:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=WS(e=GS(i),jS))=="string"?t:YS?La(e):(r=La(e))=="Object"&&US(e.callee)?"Arguments":r}});var ed=b((uk,Zc)=>{"use strict";var QS=Ra(),zS=vr();Zc.exports=QS?{}.toString:function(){return"[object "+zS(this)+"]"}});var $a=b((lk,rd)=>{"use strict";var KS=Ra(),JS=qt().f,XS=Ut(),ZS=We(),ey=ed(),ty=be(),td=ty("toStringTag");rd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;ZS(a,td)||JS(a,td,{configurable:!0,value:e}),r&&!KS&&XS(a,"toString",ey)}}});var ad=b((ck,id)=>{"use strict";var ry=Ln().IteratorPrototype,iy=xn(),ay=Wr(),sy=$a(),ny=Ft(),oy=function(){return this};id.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=iy(ry,{next:ay(+!r,t)}),sy(i,a,!1,!0),ny[a]=oy,i}});var nd=b((dk,sd)=>{"use strict";var uy=Ie(),ly=ut();sd.exports=function(i,e,t){try{return uy(ly(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var ud=b((pk,od)=>{"use strict";var cy=se(),dy=String,py=TypeError;od.exports=function(i){if(typeof i=="object"||cy(i))return i;throw py("Can't set "+dy(i)+" as a prototype")}});var $n=b((hk,ld)=>{"use strict";var hy=nd(),fy=je(),my=ud();ld.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=hy(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return fy(a),my(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var yd=b((fk,Sd)=>{"use strict";var by=Oe(),gy=Ee(),Ca=Ye(),gd=fc(),vy=se(),Sy=ad(),cd=wn(),dd=$n(),yy=$a(),Ty=Ut(),Cn=gr(),Iy=be(),pd=Ft(),vd=Ln(),Ey=gd.PROPER,xy=gd.CONFIGURABLE,hd=vd.IteratorPrototype,Da=vd.BUGGY_SAFARI_ITERATORS,Jr=Iy("iterator"),fd="keys",Xr="values",md="entries",bd=function(){return this};Sd.exports=function(i,e,t,r,a,s,n){Sy(t,e,r);var o=function(y){if(y===a&&p)return p;if(!Da&&y in c)return c[y];switch(y){case fd:return function(){return new t(this,y)};case Xr:return function(){return new t(this,y)};case md:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[Jr]||c["@@iterator"]||a&&c[a],p=!Da&&d||o(a),f=e=="Array"&&c.entries||d,m,g,S;if(f&&(m=cd(f.call(new i)),m!==Object.prototype&&m.next&&(!Ca&&cd(m)!==hd&&(dd?dd(m,hd):vy(m[Jr])||Cn(m,Jr,bd)),yy(m,u,!0,!0),Ca&&(pd[u]=bd))),Ey&&a==Xr&&d&&d.name!==Xr&&(!Ca&&xy?Ty(c,"name",Xr):(l=!0,p=function(){return gy(d,this)})),a)if(g={values:o(Xr),keys:s?p:o(fd),entries:o(md)},n)for(S in g)(Da||l||!(S in c))&&Cn(c,S,g[S]);else by({target:e,proto:!0,forced:Da||l},g);return(!Ca||n)&&c[Jr]!==p&&Cn(c,Jr,p,{name:a}),pd[e]=p,g}});var Id=b((mk,Td)=>{"use strict";Td.exports=function(i,e){return{value:i,done:e}}});var Mn=b((bk,kd)=>{"use strict";var Py=hr(),Dn=_s(),Ed=Ft(),Pd=dn(),wy=qt().f,ky=yd(),Ma=Id(),Ay=Ye(),Ry=et(),wd="Array Iterator",Ly=Pd.set,$y=Pd.getterFor(wd);kd.exports=ky(Array,"Array",function(i,e){Ly(this,{type:wd,target:Py(i),index:0,kind:e})},function(){var i=$y(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Ma(void 0,!0)):t=="keys"?Ma(r,!1):t=="values"?Ma(e[r],!1):Ma([r,e[r]],!1)},"values");var xd=Ed.Arguments=Ed.Array;Dn("keys");Dn("values");Dn("entries");if(!Ay&&Ry&&xd.name!=="values")try{wy(xd,"name",{value:"values"})}catch(i){}});var Rd=b((gk,Ad)=>{"use strict";var Cy=be(),Dy=Ft(),My=Cy("iterator"),Oy=Array.prototype;Ad.exports=function(i){return i!==void 0&&(Dy.Array===i||Oy[My]===i)}});var On=b((vk,$d)=>{"use strict";var By=vr(),Ld=Gr(),Vy=pr(),_y=Ft(),Ny=be(),Fy=Ny("iterator");$d.exports=function(i){if(!Vy(i))return Ld(i,Fy)||Ld(i,"@@iterator")||_y[By(i)]}});var Dd=b((Sk,Cd)=>{"use strict";var qy=Ee(),Uy=ut(),Hy=je(),jy=jr(),Gy=On(),Yy=TypeError;Cd.exports=function(i,e){var t=arguments.length<2?Gy(i):e;if(Uy(t))return Hy(qy(t,i));throw Yy(jy(i)+" is not iterable")}});var Bd=b((yk,Od)=>{"use strict";var Wy=Ee(),Md=je(),Qy=Gr();Od.exports=function(i,e,t){var r,a;Md(i);try{if(r=Qy(i,"return"),!r){if(e==="throw")throw t;return t}r=Wy(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Md(r),t}});var Ba=b((Tk,Fd)=>{"use strict";var zy=Kr(),Ky=Ee(),Jy=je(),Xy=jr(),Zy=Rd(),eT=wa(),Vd=Ur(),tT=Dd(),rT=On(),_d=Bd(),iT=TypeError,Oa=function(i,e){this.stopped=i,this.result=e},Nd=Oa.prototype;Fd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=zy(e,r),l,c,d,p,f,m,g,S=function(v){return l&&_d(l,"normal",v),new Oa(!0,v)},y=function(v){return a?(Jy(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(s)l=i.iterator;else if(n)l=i;else{if(c=rT(i),!c)throw iT(Xy(i)+" is not iterable");if(Zy(c)){for(d=0,p=eT(i);p>d;d++)if(f=y(i[d]),f&&Vd(Nd,f))return f;return new Oa(!1)}l=tT(i,c)}for(m=s?i.next:l.next;!(g=Ky(m,l)).done;){try{f=y(g.value)}catch(v){_d(l,"throw",v)}if(typeof f=="object"&&f&&Vd(Nd,f))return f}return new Oa(!1)}});var Ud=b((Ik,qd)=>{"use strict";var aT=va(),sT=qt(),nT=Wr();qd.exports=function(i,e,t){var r=aT(e);r in i?sT.f(i,r,nT(0,t)):i[r]=t}});var Hd=b(()=>{"use strict";var oT=Oe(),uT=Ba(),lT=Ud();oT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uT(e,function(r,a){lT(t,r,a)},{AS_ENTRIES:!0}),t}})});var Gd=b((Pk,jd)=>{"use strict";Mn();Hd();var cT=ma();jd.exports=cT.Object.fromEntries});var Wd=b((wk,Yd)=>{"use strict";Yd.exports={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}});var Kd=b(()=>{"use strict";Mn();var dT=Wd(),pT=he(),hT=vr(),fT=Ut(),Qd=Ft(),mT=be(),zd=mT("toStringTag");for(Va in dT)Bn=pT[Va],_a=Bn&&Bn.prototype,_a&&hT(_a)!==zd&&fT(_a,zd,Va),Qd[Va]=Qd.Array;var Bn,_a,Va});var Xd=b((Rk,Jd)=>{"use strict";var bT=Gd();Kd();Jd.exports=bT});var Na=b((Lk,Zd)=>{"use strict";var gT=Xd();Zd.exports=gT});var ep=b(()=>{"use strict"});var Zr=b((Dk,tp)=>{"use strict";var vT=dr();tp.exports=typeof process!="undefined"&&vT(process)=="process"});var ip=b((Mk,rp)=>{"use strict";var ST=qt();rp.exports=function(i,e,t){return ST.f(i,e,t)}});var np=b((Ok,sp)=>{"use strict";var yT=ot(),TT=ip(),IT=be(),ET=et(),ap=IT("species");sp.exports=function(i){var e=yT(i);ET&&e&&!e[ap]&&TT(e,ap,{configurable:!0,get:function(){return this}})}});var up=b((Bk,op)=>{"use strict";var xT=Ur(),PT=TypeError;op.exports=function(i,e){if(xT(e,i))return i;throw PT("Incorrect invocation")}});var _n=b((Vk,lp)=>{"use strict";var wT=Ie(),kT=se(),Vn=ga(),AT=wT(Function.toString);kT(Vn.inspectSource)||(Vn.inspectSource=function(i){return AT(i)});lp.exports=Vn.inspectSource});var mp=b((_k,fp)=>{"use strict";var RT=Ie(),LT=Le(),cp=se(),$T=vr(),CT=ot(),DT=_n(),dp=function(){},MT=[],pp=CT("Reflect","construct"),Nn=/^\s*(?:class|function)\b/,OT=RT(Nn.exec),BT=!Nn.exec(dp),ei=function(e){if(!cp(e))return!1;try{return pp(dp,MT,e),!0}catch(t){return!1}},hp=function(e){if(!cp(e))return!1;switch($T(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return BT||!!OT(Nn,DT(e))}catch(t){return!0}};hp.sham=!0;fp.exports=!pp||LT(function(){var i;return ei(ei.call)||!ei(Object)||!ei(function(){i=!0})||i})?hp:ei});var gp=b((Nk,bp)=>{"use strict";var VT=mp(),_T=jr(),NT=TypeError;bp.exports=function(i){if(VT(i))return i;throw NT(_T(i)+" is not a constructor")}});var Fn=b((Fk,Sp)=>{"use strict";var vp=je(),FT=gp(),qT=pr(),UT=be(),HT=UT("species");Sp.exports=function(i,e){var t=vp(i).constructor,r;return t===void 0||qT(r=vp(t)[HT])?e:FT(r)}});var Tp=b((qk,yp)=>{"use strict";var jT=Ie();yp.exports=jT([].slice)});var Ep=b((Uk,Ip)=>{"use strict";var GT=TypeError;Ip.exports=function(i,e){if(i<e)throw GT("Not enough arguments");return i}});var qn=b((Hk,xp)=>{"use strict";var YT=Hr();xp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(YT)});var Kn=b((jk,Dp)=>{"use strict";var $e=he(),WT=pn(),QT=Kr(),Pp=se(),zT=We(),Cp=Le(),wp=yn(),KT=Tp(),kp=ha(),JT=Ep(),XT=qn(),ZT=Zr(),Wn=$e.setImmediate,Qn=$e.clearImmediate,eI=$e.process,Un=$e.Dispatch,tI=$e.Function,Ap=$e.MessageChannel,rI=$e.String,Hn=0,ti={},Rp="onreadystatechange",ri,jt,jn,Gn;Cp(function(){ri=$e.location});var zn=function(i){if(zT(ti,i)){var e=ti[i];delete ti[i],e()}},Yn=function(i){return function(){zn(i)}},Lp=function(i){zn(i.data)},$p=function(i){$e.postMessage(rI(i),ri.protocol+"//"+ri.host)};(!Wn||!Qn)&&(Wn=function(e){JT(arguments.length,1);var t=Pp(e)?e:tI(e),r=KT(arguments,1);return ti[++Hn]=function(){WT(t,void 0,r)},jt(Hn),Hn},Qn=function(e){delete ti[e]},ZT?jt=function(i){eI.nextTick(Yn(i))}:Un&&Un.now?jt=function(i){Un.now(Yn(i))}:Ap&&!XT?(jn=new Ap,Gn=jn.port2,jn.port1.onmessage=Lp,jt=QT(Gn.postMessage,Gn)):$e.addEventListener&&Pp($e.postMessage)&&!$e.importScripts&&ri&&ri.protocol!=="file:"&&!Cp($p)?(jt=$p,$e.addEventListener("message",Lp,!1)):Rp in kp("script")?jt=function(i){wp.appendChild(kp("script"))[Rp]=function(){wp.removeChild(this),zn(i)}}:jt=function(i){setTimeout(Yn(i),0)});Dp.exports={set:Wn,clear:Qn}});var Jn=b((Gk,Op)=>{"use strict";var Mp=function(){this.head=null,this.tail=null};Mp.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Op.exports=Mp});var Vp=b((Yk,Bp)=>{"use strict";var iI=Hr();Bp.exports=/ipad|iphone|ipod/i.test(iI)&&typeof Pebble!="undefined"});var Np=b((Wk,_p)=>{"use strict";var aI=Hr();_p.exports=/web0s(?!.*chrome)/i.test(aI)});var Wp=b((Qk,Yp)=>{"use strict";var Gt=he(),Fp=Kr(),sI=fn().f,Xn=Kn().set,nI=Jn(),oI=qn(),uI=Vp(),lI=Np(),Zn=Zr(),qp=Gt.MutationObserver||Gt.WebKitMutationObserver,Up=Gt.document,Hp=Gt.process,Fa=Gt.Promise,jp=sI(Gt,"queueMicrotask"),ro=jp&&jp.value,Sr,eo,to,qa,Gp;ro||(ii=new nI,ai=function(){var i,e;for(Zn&&(i=Hp.domain)&&i.exit();e=ii.get();)try{e()}catch(t){throw ii.head&&Sr(),t}i&&i.enter()},!oI&&!Zn&&!lI&&qp&&Up?(eo=!0,to=Up.createTextNode(""),new qp(ai).observe(to,{characterData:!0}),Sr=function(){to.data=eo=!eo}):!uI&&Fa&&Fa.resolve?(qa=Fa.resolve(void 0),qa.constructor=Fa,Gp=Fp(qa.then,qa),Sr=function(){Gp(ai)}):Zn?Sr=function(){Hp.nextTick(ai)}:(Xn=Fp(Xn,Gt),Sr=function(){Xn(ai)}),ro=function(i){ii.head||Sr(),ii.add(i)});var ii,ai;Yp.exports=ro});var zp=b((zk,Qp)=>{"use strict";Qp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Ua=b((Kk,Kp)=>{"use strict";Kp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Yt=b((Jk,Jp)=>{"use strict";var cI=he();Jp.exports=cI.Promise});var io=b((Xk,Xp)=>{"use strict";Xp.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var eh=b((Zk,Zp)=>{"use strict";var dI=io(),pI=Zr();Zp.exports=!dI&&!pI&&typeof window=="object"&&typeof document=="object"});var yr=b((eA,ih)=>{"use strict";var hI=he(),si=Yt(),fI=se(),mI=mn(),bI=_n(),gI=be(),vI=eh(),SI=io(),yI=Ye(),ao=Ws(),th=si&&si.prototype,TI=gI("species"),so=!1,rh=fI(hI.PromiseRejectionEvent),II=mI("Promise",function(){var i=bI(si),e=i!==String(si);if(!e&&ao===66||yI&&!(th.catch&&th.finally))return!0;if(!ao||ao<51||!/native code/.test(i)){var t=new si(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[TI]=r,so=t.then(function(){})instanceof r,!so)return!0}return!e&&(vI||SI)&&!rh});ih.exports={CONSTRUCTOR:II,REJECTION_EVENT:rh,SUBCLASSING:so}});var Tr=b((tA,sh)=>{"use strict";var ah=ut(),EI=TypeError,xI=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw EI("Bad Promise constructor");e=r,t=a}),this.resolve=ah(e),this.reject=ah(t)};sh.exports.f=function(i){return new xI(i)}});var xh=b(()=>{"use strict";var PI=Oe(),wI=Ye(),Ya=Zr(),kt=he(),Pr=Ee(),nh=gr(),oh=$n(),kI=$a(),AI=np(),RI=ut(),Ga=se(),LI=Ze(),$I=up(),CI=Fn(),ph=Kn().set,co=Wp(),DI=zp(),MI=Ua(),OI=Jn(),hh=dn(),Wa=Yt(),po=yr(),fh=Tr(),Qa="Promise",mh=po.CONSTRUCTOR,BI=po.REJECTION_EVENT,VI=po.SUBCLASSING,no=hh.getterFor(Qa),_I=hh.set,Ir=Wa&&Wa.prototype,Wt=Wa,Ha=Ir,bh=kt.TypeError,oo=kt.document,ho=kt.process,uo=fh.f,NI=uo,FI=!!(oo&&oo.createEvent&&kt.dispatchEvent),gh="unhandledrejection",qI="rejectionhandled",uh=0,vh=1,UI=2,fo=1,Sh=2,ja,lh,HI,ch,yh=function(i){var e;return LI(i)&&Ga(e=i.then)?e:!1},Th=function(i,e){var t=e.value,r=e.state==vh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Sh&&GI(e),e.rejection=fo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(bh("Promise-chain cycle")):(l=yh(u))?Pr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ih=function(i,e){i.notified||(i.notified=!0,co(function(){for(var t=i.reactions,r;r=t.get();)Th(r,i);i.notified=!1,e&&!i.rejection&&jI(i)}))},Eh=function(i,e,t){var r,a;FI?(r=oo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),kt.dispatchEvent(r)):r={promise:e,reason:t},!BI&&(a=kt["on"+i])?a(r):i===gh&&DI("Unhandled promise rejection",t)},jI=function(i){Pr(ph,kt,function(){var e=i.facade,t=i.value,r=dh(i),a;if(r&&(a=MI(function(){Ya?ho.emit("unhandledRejection",t,e):Eh(gh,e,t)}),i.rejection=Ya||dh(i)?Sh:fo,a.error))throw a.value})},dh=function(i){return i.rejection!==fo&&!i.parent},GI=function(i){Pr(ph,kt,function(){var e=i.facade;Ya?ho.emit("rejectionHandled",e):Eh(qI,e,i.value)})},Er=function(i,e,t){return function(r){i(e,r,t)}},xr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=UI,Ih(i,!0))},lo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw bh("Promise can't be resolved itself");var r=yh(e);r?co(function(){var a={done:!1};try{Pr(r,e,Er(lo,a,i),Er(xr,a,i))}catch(s){xr(a,s,i)}}):(i.value=e,i.state=vh,Ih(i,!1))}catch(a){xr({done:!1},a,i)}}};if(mh&&(Wt=function(e){$I(this,Ha),RI(e),Pr(ja,this);var t=no(this);try{e(Er(lo,t),Er(xr,t))}catch(r){xr(t,r)}},Ha=Wt.prototype,ja=function(e){_I(this,{type:Qa,done:!1,notified:!1,parent:!1,reactions:new OI,rejection:!1,state:uh,value:void 0})},ja.prototype=nh(Ha,"then",function(e,t){var r=no(this),a=uo(CI(this,Wt));return r.parent=!0,a.ok=Ga(e)?e:!0,a.fail=Ga(t)&&t,a.domain=Ya?ho.domain:void 0,r.state==uh?r.reactions.add(a):co(function(){Th(a,r)}),a.promise}),lh=function(){var i=new ja,e=no(i);this.promise=i,this.resolve=Er(lo,e),this.reject=Er(xr,e)},fh.f=uo=function(i){return i===Wt||i===HI?new lh(i):NI(i)},!wI&&Ga(Wa)&&Ir!==Object.prototype)){ch=Ir.then,VI||nh(Ir,"then",function(e,t){var r=this;return new Wt(function(a,s){Pr(ch,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Ir.constructor}catch(i){}oh&&oh(Ir,Ha)}PI({global:!0,constructor:!0,wrap:!0,forced:mh},{Promise:Wt});kI(Wt,Qa,!1,!0);AI(Qa)});var Rh=b((aA,Ah)=>{"use strict";var YI=be(),wh=YI("iterator"),kh=!1;try{Ph=0,mo={next:function(){return{done:!!Ph++}},return:function(){kh=!0}},mo[wh]=function(){return this},Array.from(mo,function(){throw 2})}catch(i){}var Ph,mo;Ah.exports=function(i,e){if(!e&&!kh)return!1;var t=!1;try{var r={};r[wh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var bo=b((sA,Lh)=>{"use strict";var WI=Yt(),QI=Rh(),zI=yr().CONSTRUCTOR;Lh.exports=zI||!QI(function(i){WI.all(i).then(void 0,function(){})})});var $h=b(()=>{"use strict";var KI=Oe(),JI=Ee(),XI=ut(),ZI=Tr(),eE=Ua(),tE=Ba(),rE=bo();KI({target:"Promise",stat:!0,forced:rE},{all:function(e){var t=this,r=ZI.f(t),a=r.resolve,s=r.reject,n=eE(function(){var o=XI(t.resolve),u=[],l=0,c=1;tE(e,function(d){var p=l++,f=!1;c++,JI(o,t,d).then(function(m){f||(f=!0,u[p]=m,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var Dh=b(()=>{"use strict";var iE=Oe(),aE=Ye(),sE=yr().CONSTRUCTOR,vo=Yt(),nE=ot(),oE=se(),uE=gr(),Ch=vo&&vo.prototype;iE({target:"Promise",proto:!0,forced:sE,real:!0},{catch:function(i){return this.then(void 0,i)}});!aE&&oE(vo)&&(go=nE("Promise").prototype.catch,Ch.catch!==go&&uE(Ch,"catch",go,{unsafe:!0}));var go});var Mh=b(()=>{"use strict";var lE=Oe(),cE=Ee(),dE=ut(),pE=Tr(),hE=Ua(),fE=Ba(),mE=bo();lE({target:"Promise",stat:!0,forced:mE},{race:function(e){var t=this,r=pE.f(t),a=r.reject,s=hE(function(){var n=dE(t.resolve);fE(e,function(o){cE(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Oh=b(()=>{"use strict";var bE=Oe(),gE=Ee(),vE=Tr(),SE=yr().CONSTRUCTOR;bE({target:"Promise",stat:!0,forced:SE},{reject:function(e){var t=vE.f(this);return gE(t.reject,void 0,e),t.promise}})});var So=b((fA,Bh)=>{"use strict";var yE=je(),TE=Ze(),IE=Tr();Bh.exports=function(i,e){if(yE(i),TE(e)&&e.constructor===i)return e;var t=IE.f(i),r=t.resolve;return r(e),t.promise}});var Nh=b(()=>{"use strict";var EE=Oe(),xE=ot(),Vh=Ye(),PE=Yt(),_h=yr().CONSTRUCTOR,wE=So(),kE=xE("Promise"),AE=Vh&&!_h;EE({target:"Promise",stat:!0,forced:Vh||_h},{resolve:function(e){return wE(AE&&this===kE?PE:this,e)}})});var Fh=b(()=>{"use strict";xh();$h();Dh();Mh();Oh();Nh()});var jh=b(()=>{"use strict";var RE=Oe(),LE=Ye(),za=Yt(),$E=Le(),Uh=ot(),Hh=se(),CE=Fn(),qh=So(),DE=gr(),To=za&&za.prototype,ME=!!za&&$E(function(){To.finally.call({then:function(){}},function(){})});RE({target:"Promise",proto:!0,real:!0,forced:ME},{finally:function(i){var e=CE(this,Uh("Promise")),t=Hh(i);return this.then(t?function(r){return qh(e,i()).then(function(){return r})}:i,t?function(r){return qh(e,i()).then(function(){throw r})}:i)}});!LE&&Hh(za)&&(yo=Uh("Promise").prototype.finally,To.finally!==yo&&DE(To,"finally",yo,{unsafe:!0}));var yo});var Ka=b((TA,Gh)=>{"use strict";var OE=ot();Gh.exports=OE});var Wh=b((IA,Yh)=>{"use strict";ep();Fh();jh();var BE=Ka();Yh.exports=BE("Promise","finally")});var zh=b((EA,Qh)=>{"use strict";var VE=Wh();Qh.exports=VE});var Ja=b((xA,Kh)=>{"use strict";var _E=zh();Kh.exports=_E});var nf=b(()=>{"use strict";var GE=Oe(),YE=Yr(),WE=wa(),QE=Pa(),zE=_s();GE({target:"Array",proto:!0},{at:function(e){var t=YE(this),r=WE(t),a=QE(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});zE("at")});var uf=b((PR,of)=>{"use strict";nf();var KE=Ka();of.exports=KE("Array","at")});var cf=b((wR,lf)=>{"use strict";var JE=uf();lf.exports=JE});var Za=b((kR,df)=>{"use strict";var XE=cf();df.exports=XE});var Cf=b(()=>{"use strict"});var Df=b(()=>{"use strict"});var Of=b((lD,Mf)=>{"use strict";var Ax=Ze(),Rx=dr(),Lx=be(),$x=Lx("match");Mf.exports=function(i){var e;return Ax(i)&&((e=i[$x])!==void 0?!!e:Rx(i)=="RegExp")}});var Vf=b((cD,Bf)=>{"use strict";var Cx=vr(),Dx=String;Bf.exports=function(i){if(Cx(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Dx(i)}});var Nf=b((dD,_f)=>{"use strict";var Mx=je();_f.exports=function(){var i=Mx(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var Uf=b((pD,qf)=>{"use strict";var Ox=Ee(),Bx=We(),Vx=Ur(),_x=Nf(),Ff=RegExp.prototype;qf.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Ff)&&!Bx(i,"flags")&&Vx(Ff,i)?Ox(_x,i):e}});var jf=b((hD,Hf)=>{"use strict";var qo=Ie(),Nx=Yr(),Fx=Math.floor,No=qo("".charAt),qx=qo("".replace),Fo=qo("".slice),Ux=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Hx=/\$([$&'`]|\d{1,2})/g;Hf.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=Hx;return a!==void 0&&(a=Nx(a),u=Ux),qx(s,u,function(l,c){var d;switch(No(c,0)){case"$":return"$";case"&":return i;case"`":return Fo(e,0,t);case"'":return Fo(e,n);case"<":d=a[Fo(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var f=Fx(p/10);return f===0?l:f<=o?r[f-1]===void 0?No(c,1):r[f-1]+No(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var zf=b(()=>{"use strict";var jx=Oe(),Gx=Ee(),Uo=Ie(),Gf=da(),Yx=se(),Wx=pr(),Qx=Of(),Lr=Vf(),zx=Gr(),Kx=Uf(),Jx=jf(),Xx=be(),Zx=Ye(),eP=Xx("replace"),tP=TypeError,Qf=Uo("".indexOf),rP=Uo("".replace),Yf=Uo("".slice),iP=Math.max,Wf=function(i,e,t){return t>i.length?-1:e===""?t:Qf(i,e,t)};jx({target:"String",proto:!0},{replaceAll:function(e,t){var r=Gf(this),a,s,n,o,u,l,c,d,p,f=0,m=0,g="";if(!Wx(e)){if(a=Qx(e),a&&(s=Lr(Gf(Kx(e))),!~Qf(s,"g")))throw tP("`.replaceAll` does not allow non-global regexes");if(n=zx(e,eP),n)return Gx(n,e,r,t);if(Zx&&a)return rP(Lr(r),e,t)}for(o=Lr(r),u=Lr(e),l=Yx(t),l||(t=Lr(t)),c=u.length,d=iP(1,c),f=Wf(o,u,0);f!==-1;)p=l?Lr(t(u,f,o)):Jx(u,o,f,[],void 0,t),g+=Yf(o,m,f)+p,m=f+c,f=Wf(o,u,f+d);return m<o.length&&(g+=Yf(o,m)),g}})});var Jf=b((bD,Kf)=>{"use strict";Cf();Df();zf();var aP=Ka();Kf.exports=aP("String","replaceAll")});var Zf=b((gD,Xf)=>{"use strict";var sP=Jf();Xf.exports=sP});var tm=b((vD,em)=>{"use strict";var nP=Zf();em.exports=nP});var AP={};Eb(AP,{ChromecastState:()=>Fr,HttpConnectionType:()=>ua,Observable:()=>st.Observable,PlaybackState:()=>Te,Player:()=>Zi,SDK_VERSION:()=>kP,Subject:()=>st.Subject,Subscription:()=>st.Subscription,Surface:()=>la,VERSION:()=>Os,ValueSubject:()=>st.ValueSubject,VideoFormat:()=>wt,VideoQuality:()=>st.VideoQuality});module.exports=xb(AP);var Os="__VERSION__";var Te=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(Te||{}),wt=(v=>(v.MPEG="MPEG",v.DASH="DASH_SEP",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(wt||{});var Fr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Fr||{}),ua=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ua||{});var la=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(la||{});var N=require("@vkontakte/videoplayer-shared");var Eu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ca=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,N.isNonNullable)((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Eu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?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(0,N.assertNever)(a.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,N.map)(a=>a.castState)),(0,N.observableFrom)([r.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(wb),(0,N.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=(0,N.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();(0,N.assertNonNullable)(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,N.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,N.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},wb=i=>{switch(i){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(0,N.assertNever)(i)}};var jm=He(Na(),1);var ef=He(Ja(),1);var Io=require("@vkontakte/videoplayer-shared");var ge=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,Io.assertNever)(t)}return i},Eo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Io.assertNever)(e)}};var k=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var tt=require("@vkontakte/videoplayer-shared"),G=class{constructor(e){this.transitionStarted$=new tt.Subject;this.transitionEnded$=new tt.Subject;this.transitionUpdated$=new tt.Subject;this.forceChanged$=new tt.Subject;this.stateChangeStarted$=(0,tt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,tt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,tt.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Jh=require("@vkontakte/videoplayer-shared"),Xh=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Jh.assertNever)(i)}};var L=require("@vkontakte/videoplayer-shared");var NE=5,FE=5,qE=500,Zh=7e3,ni=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Xh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let 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);let e=new L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new L.Subject;e.add(a.pipe((0,L.debounce)(qE)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>NE)&&a.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.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()&&s.duration-s.currentTime<FE&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];(0,L.assertNonNullable)(c);let d=(0,L.getHighestQuality)(Object.keys(c));(0,L.assertNonNullable)(d);let p=c[d];(0,L.assertNonNullable)(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=ge(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(Zh).subscribe(()=>s(`timeout(${Zh})`)))});(0,ef.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var oi=i=>{i.removeAttribute("src"),i.load()};var tf=i=>{try{i.pause(),i.playbackRate=0,oi(i),i.remove()}catch(e){console.error(e)}};var xo=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Po=window.WeakMap?new WeakMap:new xo,xe=i=>{let e=i.querySelector("video"),t=!!e;return e?oi(e):(e=document.createElement("video"),i.appendChild(e)),Po.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Pe=i=>{let e=Po.get(i);Po.delete(i),e?oi(i):tf(i)};var $=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),Xa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=(0,At.isNullable)(a),l=new At.Subscription;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},rt=(i,e,t)=>Xa(e,()=>i.loop,r=>{(0,At.isNonNullable)(r)&&(i.loop=r)},{onError:t}),we=(i,e,t,r)=>Xa(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,At.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Be=(i,e,t,r)=>Xa(e,()=>i.playbackRate,a=>{(0,At.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Rt=Xa;var UE=i=>["__",i.language,i.label].join("|"),HE=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},wo=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Rt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Rt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Rt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(Rt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var l,c,d,p,f;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(f=o.target)==null||f.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,a=e.id?e.id:UE(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(a))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!HE(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,$.assertNonNullable)(this.video);let 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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ve=wo;var dt=class{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,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var rf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ko=i=>{let e=rf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},af=i=>{let e=rf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var R=require("@vkontakte/videoplayer-shared");var jE=3,sf=(i,e,t=jE)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var ke=i=>{let e=E=>(0,R.fromEvent)(i,E).pipe((0,R.mapTo)(void 0)),r=(0,R.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>(0,R.fromEvent)(i,E))).pipe((0,R.map)(E=>E.type==="ended"?i.readyState<2:i.readyState<3),(0,R.filterChanged)()),a=(0,R.merge)((0,R.fromEvent)(i,"progress"),(0,R.fromEvent)(i,"timeupdate")).pipe((0,R.map)(()=>sf(i.buffered,i.currentTime))),n=(0,R.getCurrentBrowser)().browser===R.CurrentClientBrowser.Safari?(0,R.combine)({play:e("play").pipe((0,R.once)()),playing:e("playing")}).pipe((0,R.mapTo)(void 0)):e("playing"),o=(0,R.fromEvent)(i,"volumechange").pipe((0,R.map)(()=>({muted:i.muted,volume:i.volume}))),u=(0,R.fromEvent)(i,"ratechange").pipe((0,R.map)(()=>i.playbackRate)),l=(0,R.fromEvent)(i,"error").pipe((0,R.filter)(()=>!!(i.error||i.played.length)),(0,R.map)(()=>{var x;let E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(x=i.error)!=null?x:void 0}})),c=(0,R.fromEvent)(i,"timeupdate").pipe((0,R.map)(()=>i.currentTime)),d=new R.Subject,p=.3,f;c.subscribe(E=>{i.loop&&(0,R.isNonNullable)(f)&&(0,R.isNonNullable)(E)&&f>=i.duration-p&&E<=p&&d.next(f),f=E});let m=(0,R.fromEvent)(i,"enterpictureinpicture"),g=(0,R.fromEvent)(i,"leavepictureinpicture"),S=new R.ValueSubject(af(i));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let y=new R.ValueSubject(ko(i));return(0,R.fromEvent)(i,"fullscreenchange").pipe((0,R.map)(()=>ko(i))).subscribe(y),{playing$:n,pause$:e("pause").pipe((0,R.filter)(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,R.fromEvent)(i,"durationchange").pipe((0,R.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:S,inFullscreen$:y}};var pt=require("@vkontakte/videoplayer-shared"),Lt=i=>{switch(i){case"mobile":return pt.VideoQuality.Q_144P;case"lowest":return pt.VideoQuality.Q_240P;case"low":return pt.VideoQuality.Q_360P;case"sd":case"medium":return pt.VideoQuality.Q_480P;case"hd":case"high":return pt.VideoQuality.Q_720P;case"fullhd":case"full":return pt.VideoQuality.Q_1080P;case"quadhd":case"quad":return pt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return pt.VideoQuality.Q_2160P}};var Ro=He(Za(),1),U=require("@vkontakte/videoplayer-shared");var Ao=!1,ht={},pf=i=>{Ao=i},hf=()=>{ht={}},ff=i=>{i(ht)},ui=(i,e)=>{var t;Ao&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[i]=e)},Se=class{constructor(e){this.name=e}next(e){var r,a;if(!Ao)return;ht.series=(r=ht.series)!=null?r:{};let t=(a=ht.series[this.name])!=null?a:[];t.push([Date.now(),e]),ht.series[this.name]=t}};var ZE=new Se("best_bitrate"),ex=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,es=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,U.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tx='Assertion "ABR Tracks is empty array" failed',rx=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var re,q,D,te,ce;(0,U.assertNotEmptyArray)(i,tx);let p=r.usePixelRatio&&(re=window.devicePixelRatio)!=null?re:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},m=f&&(0,U.videoSizeToQuality)(f),g=r.considerPlaybackRate&&(0,U.isNonNullable)(o)?o:1,S=i.filter(V=>!(0,U.isInvariantQuality)(V.quality)).sort((V,A)=>(0,U.isHigher)(V.quality,A.quality)?-1:1),y=(q=(0,Ro.default)(S,-1))==null?void 0:q.quality,v=(D=(0,Ro.default)(S,0))==null?void 0:D.quality,E=(0,U.isNullable)(a)||(0,U.isNonNullable)(a.min)&&(0,U.isNonNullable)(a.max)&&(0,U.isLower)(a.max,a.min)||(0,U.isNonNullable)(a.min)&&v&&(0,U.isHigher)(a.min,v)||(0,U.isNonNullable)(a.max)&&y&&(0,U.isLower)(a.max,y),x=g*ex(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),P={},Y=S.filter(V=>(m?(0,U.isLower)(V.quality,m):!0)?((0,U.isNonNullable)(t)&&isFinite(t)&&(0,U.isNonNullable)(V.bitrate)?t-s>=V.bitrate*x:!0)?r.lazyQualitySwitch&&(0,U.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,U.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,U.isHigher)(V.quality,u.quality)?(P[V.quality]="Buffer",!1):!!c&&(0,U.isHigherOrEqual)(V.quality,c)?(P[V.quality]="DroppedFramesLimit",!1):E||((0,U.isNullable)(a.max)||(0,U.isLowerOrEqual)(V.quality,a.max))&&((0,U.isNullable)(a.min)||(0,U.isHigherOrEqual)(V.quality,a.min))?!0:(P[V.quality]="FitsQualityLimits",!1):(P[V.quality]="FitsThroughput",!1):(P[V.quality]="FitsContainer",!1))[0];Y&&Y.bitrate&&ZE.next(Y.bitrate);let j=(te=Y!=null?Y:S[Math.ceil((S.length-1)/2)])!=null?te:i[0];j.quality!==((ce=l==null?void 0:l.last)==null?void 0:ce.quality)&&d({message:`
7
7
  [available tracks]
8
- ${i.map(_=>`{ id: ${_.id}, quality: ${_.quality}, bitrate: ${_.bitrate} }`).join(`
8
+ ${i.map(V=>`{ id: ${V.id}, quality: ${V.quality}, bitrate: ${V.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(r!=null?r:{}).map(([_,P])=>`${_}: ${P}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([V,A])=>`${V}: ${A}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
- containerQualityLimit: ${T},
16
+ containerQualityLimit: ${m},
17
17
  throughput: ${t},
18
- reserve: ${n},
19
- playbackRate: ${l},
20
- playbackRateFactor: ${E},
21
- forwardBufferHealth: ${o},
18
+ reserve: ${s},
19
+ playbackRate: ${o},
20
+ playbackRateFactor: ${g},
21
+ forwardBufferHealth: ${n},
22
22
  bitrateFactor: ${x},
23
23
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${h},
25
- limitsAreInvalid: ${F},
26
- maxQualityLimit: ${s==null?void 0:s.max},
27
- minQualityLimit: ${s==null?void 0:s.min},
24
+ droppedVideoMaxQualityLimit: ${c},
25
+ limitsAreInvalid: ${E},
26
+ maxQualityLimit: ${a==null?void 0:a.max},
27
+ minQualityLimit: ${a==null?void 0:a.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(U).map(([_,P])=>`${_}: ${P}`).join(`
30
+ ${Object.entries(P).map(([V,A])=>`${V}: ${A}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${I==null?void 0:I.quality}
34
- [selected track] ${A==null?void 0:A.quality}
35
- `});const W=A&&u&&u.history[A.id]&&a.now()-u.history[A.id]<=r.trackCooldown&&(!u.last||A.id!==u.last.id);if(A!=null&&A.id&&u&&!W&&u.recordSelection(A),W&&(u!=null&&u.last)){const _=u.last;return u==null||u.recordSwitch(_),c({message:`
36
- [last selected] ${_==null?void 0:_.quality}
37
- `}),_}return u==null||u.recordSwitch(A),A};var Me=i=>new URL(i).hostname,D;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(D||(D={}));const ho=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Et=i=>G(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!ho(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return ho(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});function ue(){return a.now()}function ru(i){return ue()-i}function fo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function dS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Zi(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,h,c,f=!1,p="arraybuffer",v=7e3,m=2e3,b=()=>{if(d)return;a.assertNonNullable(h);const I=ru(h);let A;if(I<m){A=m-I,setTimeout(b,A);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,O()};const S=I=>(n=I,H),y=I=>(c=I,H),T=()=>(p="json",H),E=()=>{if(!d){if(--u>=0){b(),r&&r();return}d=!0,c&&c(),t&&t()}},$=I=>(f=I,H),O=()=>{h=ue(),o=new s,o.open("get",i);let I=0,A,W=0;const _=()=>(a.assertNonNullable(h),Math.max(h,Math.max(A||0,W||0)));if(n&&o.addEventListener("progress",P=>{const j=ue();n.updateChunk&&P.loaded>I&&(n.updateChunk(_(),P.loaded-I),I=P.loaded,A=j)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const j=o.response.byteLength-I;j&&n.updateChunk&&n.updateChunk(_(),j)}o.responseType==="json"&&!Object.values(o.response).length?E():(c&&c(),e(o.response))}else E()}),o.addEventListener("error",()=>{E()}),f){const P=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ue(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=p,o.send(),H},H={withBitrateReporting:S,withParallel:$,withJSONResponse:T,withRetryCount:I=>(u=I,H),withRetryInterval:(I,A)=>(a.isNonNullable(I)&&(m=I),a.isNonNullable(A)&&(v=A),H),withTimeout:I=>(l=I,H),withFinally:y,send:O,abort:()=>{o&&(o.abort(),o=void 0),d=!0,c&&c()}};return H}const hS=100,fS=2e3,pS=500;let mS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-pS;if(t-e>fS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>hS&&(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 vS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=ue(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zi(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_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=ue();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Hi=1e4,ms=3,bS=6e4,SS=10,gS=1,yS=500;class TS{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 mS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=fo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():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=fo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{dS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new vS(ms,Hi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,h=!1;const c=()=>{const E=n&&(!h||h===this.rep);return E||t("Not running!"),E},f=(E,$,O)=>{d&&d.abort(),d=Zi(this.urlResolver.resolve(E,!1),$,O,()=>this._retryCallback()).withTimeout(Hi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ms).withFinally(()=>{d=null}).send()},p=(E,$,O)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,O,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=E=>{const $=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),r.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const O=ue()-1e4;let M=0;for(let x=0;x<this.bufferStates.length;x++){const U=this.bufferStates[x];E=Math.min(E,U.buf),U.ts<O&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${E} drop=${M} jitter=${this.sourceJitter}`);let F=E-gS;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?v(1.15):F>1?v(1.1):F>.3?v(1.05):v(1)}},S=E=>{let $;const O=()=>$&&$.start?$.start.length:0,M=P=>$.start[P]/1e3,F=P=>$.dur[P]/1e3,x=P=>$.fragIndex+P,U=(P,j)=>({chunkIdx:x(P),startTS:M(P),dur:F(P),discontinuity:j}),H=()=>{let P=0;if($&&$.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,J=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=j;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let se=$.dur.length-1;for(;se>=0&&(ee-=$.dur[se],!(ee<=0));--se);P=Math.min(se,$.dur.length-1-J),P=Math.max(P,0)}return U(P,!0)},I=P=>{const j=O();if(!(j<=0)){if(a.isNonNullable(P)){for(let J=0;J<j;J++)if(M(J)>P)return U(J)}return H()}},A=P=>{const j=O(),J=P?P.chunkIdx+1:0,ee=J-$.fragIndex;if(!(j<=0)){if(!P||ee<0||ee-j>SS)return t(`Resync: offset=${ee} bChunks=${j} chunk=`+JSON.stringify(P)),H();if(!(ee>=j))return U(J-$.fragIndex,!1)}},W=(P,j,J)=>{u&&u.abort(),u=Zi(this.urlResolver.resolve(P,!0,this.lowLatency),j,J,()=>this._retryCallback()).withTimeout(Hi).withRetryCount(ms).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,j)=>{W(E,J=>{if(!c())return;$=J;const ee=!!$.lowLatency;ee!==this.lowLatency&&m(ee);let se=0;for(let _e=0;_e<$.dur.length;++_e)se+=$.dur[_e];se>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/$.dur.length)),s({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,P(I(j))},()=>this._handleNetworkError())},nextChunk:A}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:E=>{const{videoElement:$,logger:O}=this.params;let M=S(e.jidxUrl),F,x,U,H,I=0,A,W,_;const P=()=>{A&&(clearTimeout(A),A=void 0);const V=Math.max(yS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),oe=I+V,he=ue(),pe=Math.min(1e4,oe-he);I=he;const kt=()=>{u||c()&&M.seek(()=>{c()&&(I=ue(),j(),P())})};pe>0?A=window.setTimeout(()=>{this.paused?P():kt()},pe):kt()},j=()=>{let V;for(;V=M.nextChunk(H);)H=V,Jt(V);const oe=M.nextChunk(U);if(oe){if(U&&oe.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?P():(y(),this._initPlayerWith(e));return}_e(oe)}else P()},J=(V,oe)=>{if(!c()||!this.sourceBuffer)return;let he,pe,kt;const Xt=Ve=>{window.setTimeout(()=>{c()&&J(V,oe)},Ve)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Xt(100);else{const Ve=ue(),Se=$.currentTime;!this.paused&&$.buffered.length>1&&W===Se&&Ve-_>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),W!==Se&&(W=Se,_=Ve);const Pt=this._getBufferSizeSec();if(Pt>30)O(`Buffered ${Pt} seconds; delaying appendBuffer`),Xt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Ve,buf:Pt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),oe&&oe()}catch(Zt){if(Zt.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),kt=this.sourceBuffer.buffered.length,kt!==0&&(he=this.sourceBuffer.buffered.start(0),pe=Se,pe-he>4&&this.sourceBuffer.remove(he,pe-3)),Xt(1e3);else throw Zt}}},ee=()=>{x&&F&&(O([`Appending chunk, sz=${x.byteLength}:`,JSON.stringify(U)]),J(x,function(){x=null,j()}))},se=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),_e=V=>{c()&&p(se(V),(oe,he)=>{if(c()){if(he/=1e3,x=oe,U=V,o=V.startTS,he){const pe=Math.min(10,V.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*pe:pe}ee()}},()=>this._handleNetworkError())},Jt=V=>{c()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(V),!1)))},$t=V=>{c()&&(e.cachedHeader=V,J(V,()=>{F=!0,ee()}))};n=!0,M.seek(V=>{if(c()){if(I=ue(),!V){P();return}H=V,!a.isNullable(E)||V.startTS>E?_e(V):(U=V,j())}},E),e.cachedHeader?$t(e.cachedHeader):f(e.headerUrl,$t,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},h}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),v=c/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}f=this._selectQuality(c),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${c}`)},n=(()=>({updateChunk:(f,p)=>{const v=ue();if(this.chunkRateEstimator.addInterval(f,v,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:b}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let c=n.get();if(c&&l&&this.autoQuality){if(d&&c>l&&ru(o)<3e4)return;r(c)}d=this.autoQuality};return{updateChunk:(c,f)=>{const p=n.updateChunk(c,f);return p&&u(),p},notifySwitch:c=>{const f=ue();c<l&&(o=f),l=c}}}_fetchManifest(e,t,r){this.manifestRequest=Zi(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Hi).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){const{videoElement:e}=this.params;Et(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(D.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},bS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class su{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.Subject,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality(),s=t-this.prevTotalVideoFrames,n=r-this.prevDroppedVideoFrames,o=1-(s-n)/s;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&a.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,r)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),r=a.merge(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,r;const s=(r=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r[0];return e!=null?e:s}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Zs=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},Kt=(i,e)=>new a.Observable(t=>{if(!window.IntersectionObserver)return;const r={root:null},s=new IntersectionObserver((o,l)=>{o.forEach(d=>t.next(d.isIntersecting||Zs()))},Object.assign(Object.assign({},r),e));s.observe(i);const n=a.fromEvent(document,"visibilitychange").pipe(a.map(o=>!document.hidden||Zs())).subscribe(o=>t.next(o));return()=>{s.unobserve(i),n.unsubscribe}}),ES=[D.PAUSED,D.PLAYING,D.READY],$S=[D.PAUSED,D.PLAYING,D.READY];class kS{constructor(e){this.subscription=new a.Subscription,this.videoState=new Z(D.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new tt,this.droppedFramesManager=new su,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new Ia,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,h=[];for(const c of u){const f=(n=c.name)!==null&&n!==void 0?n:c.index.toString(10),p=(o=yr(c.name))!==null&&o!==void 0?o:a.videoSizeToQuality(c.video),v=c.bitrate/1e3,m=Object.assign({},c.video);if(!p)continue;const b={id:f,quality:p,bitrate:v,size:m};h.push({track:b,representation:c})}this.representations$.next(h),this.params.output.availableVideoTracks$.next(h.map(({track:c})=>c)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===D.MANIFEST_READY&&this.videoState.setState(D.MANIFEST_READY);break}case"qualitySwitch":{const u=s.quality,h=(d=this.representations$.getValue().find(({representation:c})=>c===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(h)&&this.params.output.currentVideoTrack$.next(h);break}case"bandwidth":{const{size:u,duration:h}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,h);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration||0),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){s!==D.STOPPED&&(this.videoState.startTransitionTo(D.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(D.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if($S.includes(s)&&(u||h)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===N.Requested&&ES.includes(s)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(s){case D.STOPPED:this.videoState.startTransitionTo(D.MANIFEST_READY),this.dash.attachSource(Ce(this.params.source.url));return;case D.MANIFEST_READY:this.videoState.startTransitionTo(D.READY),this.prepare();break;case D.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(D.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(D.PLAYING);const c=l==null?void 0:l.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play()}return;case D.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(D.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case D.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(D.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Ce(this.params.source.url,c))}return;default:return a.assertNever(s)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=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.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=Tt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(a.map(s=>s.map(({track:n})=>n)))}),this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===D.READY&&this.videoState.setState(D.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(D.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(D.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(Ti(this.video,this.params.desiredState.isLooped,t)).add(yt(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Qt(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Kt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const n=s&&a.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case D.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case D.MANIFEST_READY:case D.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case D.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case D.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),gt(this.video)}createLiveDashPlayer(){const e=new TS({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,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,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,r,s,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&a.isNonNullable(d)?d:Tr(l.map(({track:m})=>m),{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(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=h==null?void 0:h.id,f=this.params.desiredState.videoTrack.getTransition(),p=(n=this.params.desiredState.videoTrack.getState())===null||n===void 0?void 0:n.id,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(h&&(f||c!==p)&&this.setVideoTrack(h),v&&this.setAutoQuality(u),f||v||c!==p){const m=(o=l.find(({track:b})=>b.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e.id}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===D.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ce(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}}var ae;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ae||(ae={}));var De;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(De||(De={}));var ar;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ar||(ar={}));var Ee;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ee||(Ee={}));var R;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(R||(R={}));var Gt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Gt||(Gt={}));var nr;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(nr||(nr={}));var K;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(K||(K={}));var oi=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};class po{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class au extends po{constructor(){super(),this.listeners||po.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 nu=class{constructor(){Object.defineProperty(this,"signal",{value:new au,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(nu.prototype[Symbol.toStringTag]="AbortController",au.prototype[Symbol.toStringTag]="AbortSignal");function ou(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function PS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!ou({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,h){let c;h&&h.signal&&(c=h.signal,delete h.signal);const f=new t(u,h);return c&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const h=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(h){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(h.aborted)return Promise.reject(c);const f=new Promise((p,v)=>{h.addEventListener("abort",()=>v(c),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Er=ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),lu=Er?PS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,di=Er?lu.fetch:window.fetch;Er?lu.Request:window.Request;const Ht=Er?nu:window.AbortController;var ea=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const AS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},wS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",mo=wS?AS:window.requestIdleCallback;var vs,bs;const CS=16;let uu=!1;try{uu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((bs=(vs=navigator.userAgent.match(/Version\/(\d+)/))===null||vs===void 0?void 0:vs[1])!==null&&bs!==void 0?bs:"",10)<=CS}catch(i){console.error(i)}class IS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return G(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return G(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return G(this,void 0,void 0,function*(){return new Promise(t=>{let r;uu&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var vo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class be{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;const s=this.size32?this.size32-8:void 0,n=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,n,s),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class cu extends be{}class _S extends be{}class RS extends be{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){const s=this.readString(4);this.compatibleBrands.push(s),r-=4}}}class LS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class DS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class xS extends be{constructor(e,t){super(e,t),this.data=this.content}}class We extends be{constructor(e,t){super(e,t);const r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}}class du extends We{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let s=this.readUint32();const n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();const d=s>>>28,u=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:d,SAPDeltaTime:u})}}}class NS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class OS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var ht;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(ht||(ht={}));class MS extends We{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=ht.MONOSCOPIC;break;case 1:this.stereoMode=ht.TOP_BOTTOM;break;case 2:this.stereoMode=ht.LEFT_RIGHT;break;case 3:this.stereoMode=ht.STEREO_CUSTOM;break;case 4:this.stereoMode=ht.RIGHT_LEFT;break}this.cursor+=1}}class BS extends We{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class VS extends We{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class FS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class US extends We{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class jS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class HS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class GS extends We{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class YS extends be{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class qS extends We{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class WS extends We{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class zS extends We{constructor(e,t){super(e,t),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}var Q;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UuidBox="uuid",i.UnknownBox="unknown"})(Q||(Q={}));const QS={[Q.FtypBox]:RS,[Q.MoovBox]:LS,[Q.MoofBox]:DS,[Q.MdatBox]:xS,[Q.SidxBox]:du,[Q.TrakBox]:NS,[Q.MdiaBox]:FS,[Q.MfhdBox]:GS,[Q.TkhdBox]:US,[Q.TrafBox]:YS,[Q.TfhdBox]:qS,[Q.TfdtBox]:WS,[Q.TrunBox]:zS,[Q.MinfBox]:jS,[Q.Sv3dBox]:OS,[Q.St3dBox]:MS,[Q.PrhdBox]:BS,[Q.ProjBox]:HS,[Q.EquiBox]:VS,[Q.UuidBox]:_S,[Q.UnknownBox]:cu};class pt{constructor(e={}){this.options=Object.assign({offset:0},e)}parse(e){const t=[];let r=this.options.offset;for(;r<e.byteLength;)try{const n=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),o=this.createBox(n,new DataView(e.buffer,e.byteOffset+r));if(!o.size)break;t.push(o),r+=o.size}catch(s){break}return t}createBox(e,t){const r=QS[e];return r?new r(t,new pt):new cu(t,new pt)}}class Ra{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,s,n;(r=(s=this.index)[n=t.type])!==null&&r!==void 0||(s[n]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const KS=new TextDecoder("ascii"),JS=i=>KS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",XS=i=>{const e=new du(i,new pt);let t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:R.NONE,time:{from:t,to:t+o},byte:{from:r,to:r+n.referencedSize-1}};return t+=o,r+=n.referencedSize,l})},ZS=(i,e)=>{const r=new pt().parse(i),s=new Ra(r),n=s.findAll("moof"),o=e?s.findAll("uuid"):s.findAll("mdat");if(!(o.length&&n.length))return null;const l=n[0],d=o[o.length-1],u=l.source.byteOffset,c=d.source.byteOffset-l.source.byteOffset+d.size;return new DataView(i.buffer,u,c)},eg=(i,e)=>{const r=new pt().parse(i),n=new Ra(r).findAll("traf"),o=n[n.length-1].children.find(c=>c.type==="tfhd"),l=n[n.length-1].children.find(c=>c.type==="tfdt"),d=n[n.length-1].children.find(c=>c.type==="trun");let u=0;return d.sampleDuration.length?u=d.sampleDuration.reduce((c,f)=>c+f,0):u=o.defaultSampleDuration*d.sampleCount,(Number(l.baseMediaDecodeTime)+u)/e*1e3},tg=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:nr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new pt().parse(i),s=new Ra(r);if(s.find("sv3d")){e.is3dVideo=!0;const o=s.find("st3d");o&&(e.stereoMode=o.stereoMode);const l=s.find("prhd");l&&(e.projectionData.pose.yaw=l.poseYawDegrees,e.projectionData.pose.pitch=l.posePitchDegrees,e.projectionData.pose.roll=l.poseRollDegrees);const d=s.find("equi");d&&(e.projectionData.bounds.top=d.projectionBoundsTop,e.projectionData.bounds.right=d.projectionBoundsRight,e.projectionData.bounds.bottom=d.projectionBoundsBottom,e.projectionData.bounds.left=d.projectionBoundsLeft)}return e},ig={validateData:JS,parseInit:tg,getIndexRange:()=>{},parseSegments:XS,parseFeedableSegmentChunk:ZS,getSegmentEndTime:eg};var g;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(g||(g={}));var k;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(k||(k={}));const bo={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.TrackEntry]:{type:k.Master},[g.Video]:{type:k.Master},[g.Projection]:{type:k.Master},[g.ProjectionType]:{type:k.UnsignedInteger},[g.ProjectionPrivate]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},hu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=or(i,t),s=r in bo,n=s?bo[r].type:k.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,h=or(d),c=u*Math.pow(2,(l-1)*8)+h,f=t+l;let p;return f+c>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,c),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},or=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return or(i);case k.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(i);case k.UTF8:return new TextDecoder("utf-8").decode(i);case k.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case k.Master:return i;case k.Binary:return i;default:a.assertNever(e)}},Yt=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=hu(r);if(!e(s))return;s.type===k.Master&&Yt(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},rg=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,r;const s=hu(i);return Yt(s.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Ne(l,o):n===g.DocType?t=Ne(l,o):n===g.DocTypeReadVersion&&(r=Ne(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},fu=[g.Info,g.SeekHead,g.Tracks,g.TrackEntry,g.Video,g.Projection,g.ProjectionType,g.ProjectionPrivate,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],sg=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],ag=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u,h=!1;const c=0;return Yt(i,({tag:f,type:p,value:v,valueSize:m})=>{if(f===g.SeekID){const b=Ne(v,p);u=or(b)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=v.byteOffset,t=v.byteOffset+m):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?r=Ne(v,p):f===g.Duration?s=Ne(v,p):f===g.SeekPosition&&u===g.Cues?d=Ne(v,p):f===g.Tracks?Yt(v,({tag:b,type:S,value:y})=>b===g.ProjectionType?(h=Ne(y,S)===1,!1):!0):n&&o&&fu.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:c,projectionType:nr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ng=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},og=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Yt(i,({tag:l,type:d,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&s(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Ne(u,d));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Ne(u,d));break;default:t&&fu.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:h}=l,c=n[d+1];return{status:R.NONE,time:{from:u,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},lg=i=>{let e=0,t=!1;try{Yt(i,r=>r.tag===g.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):sg.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},ug={validateData:rg,parseInit:ag,getIndexRange:ng,parseSegments:og,parseFeedableSegmentChunk:lg};var cg=Ye,dg=fi,hg=de,fg=hg("match"),pg=function(i){var e;return cg(i)&&((e=i[fg])!==void 0?!!e:dg(i)=="RegExp")},mg=Si,vg=String,bg=function(i){if(mg(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return vg(i)},Sg=qe,gg=function(){var i=Sg(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},yg=ve,Tg=Be,Eg=dr,$g=gg,So=RegExp.prototype,kg=function(i){var e=i.flags;return e===void 0&&!("flags"in So)&&!Tg(i,"flags")&&Eg(So,i)?yg($g,i):e},La=ke,Pg=mr,Ag=Math.floor,Ss=La("".charAt),wg=La("".replace),gs=La("".slice),Cg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ig=/\$([$&'`]|\d{1,2})/g,_g=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,d=Ig;return s!==void 0&&(s=Pg(s),d=Cg),wg(n,d,function(u,h){var c;switch(Ss(h,0)){case"$":return"$";case"&":return i;case"`":return gs(e,0,t);case"'":return gs(e,o);case"<":c=s[gs(h,1,-1)];break;default:var f=+h;if(f===0)return u;if(f>l){var p=Ag(f/10);return p===0?u:p<=l?r[p-1]===void 0?Ss(h,1):r[p-1]+Ss(h,1):u}c=r[f-1]}return c===void 0?"":c})},Rg=Ie,Lg=ve,Da=ke,go=sa,Dg=ie,xg=pi,Ng=pg,Dt=bg,Og=pr,Mg=kg,Bg=_g,Vg=de,Fg=Vg("replace"),Ug=TypeError,pu=Da("".indexOf),jg=Da("".replace),yo=Da("".slice),Hg=Math.max,To=function(i,e,t){return t>i.length?-1:e===""?t:pu(i,e,t)};Rg({target:"String",proto:!0},{replaceAll:function(e,t){var r=go(this),s,n,o,l,d,u,h,c,f,p=0,v=0,m="";if(!xg(e)){if(s=Ng(e),s&&(n=Dt(go(Mg(e))),!~pu(n,"g")))throw Ug("`.replaceAll` does not allow non-global regexes");if(o=Og(e,Fg),o)return Lg(o,e,r,t);if(s)return jg(Dt(r),e,t)}for(l=Dt(r),d=Dt(e),u=Dg(t),u||(t=Dt(t)),h=d.length,c=Hg(1,h),p=To(l,d,0);p!==-1;)f=u?Dt(t(d,p,l)):Bg(d,l,p,[],void 0,t),m+=yo(l,v,p)+f,v=p+h,p=To(l,d,p+c);return v<l.length&&(m+=yo(l,v)),m}});var Gg=Aa,Yg=Gg("String","replaceAll"),qg=Yg,Wg=qg,zg=Wg,Qg=zg,Eo=ur(Qg);const Kg=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},$o=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Ot=(i,e)=>{let t=i;t=Eo(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=Eo(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Jg=(i,e)=>{var t,r,s,n,o,l,d,u,h,c,f,p,v,m,b,S,y,T,E,$,O,M,F,x,U,H,I,A,W,_,P,j,J,ee,se,_e,Jt,$t,V,oe,he,pe;const Xt=new DOMParser().parseFromString(i,"application/xml"),Ve={video:[],audio:[],text:[]},Se=Xt.children[0],Pt=Se.getElementsByTagName("Period")[0],Zt=(s=(r=(t=Se.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||r===void 0?void 0:r.trim())!==null&&s!==void 0?s:"",Tu=Pt.children,Eu=Se.getAttribute("type")==="dynamic",Oa=Se.getAttribute("availabilityStartTime"),$u=Oa?new Date(Oa).getTime():void 0;let it;const Ma=Se.getAttribute("mediaPresentationDuration"),Ba=Pt.getAttribute("duration"),$r=Se.getElementsByTagName("vk:Attrs")[0],Va=$r==null?void 0:$r.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Ma)it=$o(Ma);else if(Ba){const ge=$o(Ba);a.isNonNullable(ge)&&(it=ge)}else Va&&(it=parseInt(Va,10));let ku=0;const kr=(o=(n=Se.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Pu=kr.includes(ar.WEBM_AS_IN_FFMPEG)||kr.includes(ar.WEBM_AS_IN_SPEC)?Gt.WEBM:Gt.MP4;for(const ge of Tu){const Ei=ge.getAttribute("mimeType"),Au=ge.getAttribute("codecs"),Fa=(l=ge.getAttribute("contentType"))!==null&&l!==void 0?l:Ei==null?void 0:Ei.split("/")[0],wu=(u=(d=ge.getAttribute("profiles"))===null||d===void 0?void 0:d.split(","))!==null&&u!==void 0?u:[],Ua=ge.querySelectorAll("Representation"),Cu=ge.querySelector("SegmentTemplate");if(Fa===ae.TEXT){for(const te of Ua){const ze=te.getAttribute("id")||"",$i=ge.getAttribute("lang"),At=ge.getAttribute("label"),Pr=(f=(c=(h=te.querySelector("BaseURL"))===null||h===void 0?void 0:h.textContent)===null||c===void 0?void 0:c.trim())!==null&&f!==void 0?f:"",Ar=new URL(Pr||Zt,e).toString(),ki=ze.includes("_auto");Ve[ae.TEXT].push({id:ze,lang:$i,label:At,isAuto:ki,kind:ae.TEXT,url:Ar})}continue}for(const te of Ua){const ze=(p=te.getAttribute("mimeType"))!==null&&p!==void 0?p:Ei,$i=(m=(v=te.getAttribute("codecs"))!==null&&v!==void 0?v:Au)!==null&&m!==void 0?m:"",At=(S=(b=te.getAttribute("contentType"))!==null&&b!==void 0?b:ze==null?void 0:ze.split("/")[0])!==null&&S!==void 0?S:Fa,Pr=(T=(y=ge.getAttribute("profiles"))===null||y===void 0?void 0:y.split(","))!==null&&T!==void 0?T:[],Ar=parseInt((E=te.getAttribute("width"))!==null&&E!==void 0?E:"",10),ki=parseInt(($=te.getAttribute("height"))!==null&&$!==void 0?$:"",10),ja=parseInt((O=te.getAttribute("bandwidth"))!==null&&O!==void 0?O:"",10)/1e3,Ha=(M=te.getAttribute("frameRate"))!==null&&M!==void 0?M:"",Iu=(F=te.getAttribute("quality"))!==null&&F!==void 0?F:void 0,_u=Ha?Kg(Ha):void 0,Ru=(x=te.getAttribute("id"))!==null&&x!==void 0?x:(ku++).toString(10),Lu=At==="video"?`${ki}p`:At==="audio"?`${ja}Kbps`:$i,Du=`${Ru}@${Lu}`,xu=(I=(H=(U=te.querySelector("BaseURL"))===null||U===void 0?void 0:U.textContent)===null||H===void 0?void 0:H.trim())!==null&&I!==void 0?I:"",Ga=new URL(xu||Zt,e).toString(),Nu=[...kr,...wu,...Pr];let wr;const Ou=te.querySelector("SegmentBase"),rt=(A=te.querySelector("SegmentTemplate"))!==null&&A!==void 0?A:Cu;if(Ou){const st=(_=(W=te.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&_!==void 0?_:"",[at,Ir]=st.split("-").map(wt=>parseInt(wt,10)),Qe={from:at,to:Ir},ei=(P=te.querySelector("SegmentBase"))===null||P===void 0?void 0:P.getAttribute("indexRange"),[_r,Pi]=ei?ei.split("-").map(wt=>parseInt(wt,10)):[],ti=ei?{from:_r,to:Pi}:void 0;wr={type:Ee.BYTE_RANGE,url:Ga,initRange:Qe,indexRange:ti}}else if(rt){const st={representationId:(j=te.getAttribute("id"))!==null&&j!==void 0?j:void 0,bandwidth:(J=te.getAttribute("bandwidth"))!==null&&J!==void 0?J:void 0},at=parseInt((ee=rt.getAttribute("timescale"))!==null&&ee!==void 0?ee:"",10),Ir=(se=rt.getAttribute("initialization"))!==null&&se!==void 0?se:"",Qe=rt.getAttribute("media"),ei=(Jt=parseInt((_e=rt.getAttribute("startNumber"))!==null&&_e!==void 0?_e:"",10))!==null&&Jt!==void 0?Jt:1,_r=Ot(Ir,st);if(!Qe)throw new ReferenceError("No media attribute in SegmentTemplate");const Pi=($t=rt.querySelectorAll("SegmentTimeline S"))!==null&&$t!==void 0?$t:[],ti=[];let wt=0,Rr="",Lr=0;if(Pi.length){let Ai=ei,Pe=0;for(const Ct of Pi){const Re=parseInt((V=Ct.getAttribute("d"))!==null&&V!==void 0?V:"",10),nt=parseInt((oe=Ct.getAttribute("r"))!==null&&oe!==void 0?oe:"",10)||0,wi=parseInt((he=Ct.getAttribute("t"))!==null&&he!==void 0?he:"",10);Pe=Number.isFinite(wi)?wi:Pe;const Dr=Re/at*1e3,xr=Pe/at*1e3;for(let Ci=0;Ci<nt+1;Ci++){const Bu=Ot(Qe,Object.assign(Object.assign({},st),{segmentNumber:Ai.toString(10),segmentTime:(Pe+Ci*Re).toString(10)})),Ya=(xr!=null?xr:0)+Ci*Dr,Vu=Ya+Dr;Ai++,ti.push({time:{from:Ya,to:Vu},url:Bu})}Pe+=(nt+1)*Re,wt+=(nt+1)*Dr}Lr=Pe/at*1e3,Rr=Ot(Qe,Object.assign(Object.assign({},st),{segmentNumber:Ai.toString(10),segmentTime:Pe.toString(10)}))}else if(a.isNonNullable(it)){const Pe=parseInt((pe=rt.getAttribute("duration"))!==null&&pe!==void 0?pe:"",10)/at*1e3,Ct=Math.ceil(it/Pe);let Re=0;for(let nt=1;nt<Ct;nt++){const wi=Ot(Qe,Object.assign(Object.assign({},st),{segmentNumber:nt.toString(10),segmentTime:Re.toString(10)}));ti.push({time:{from:Re,to:Re+Pe},url:wi}),Re+=Pe}Lr=Re,Rr=Ot(Qe,Object.assign(Object.assign({},st),{segmentNumber:Ct.toString(10),segmentTime:Re.toString(10)}))}const Mu={time:{from:Lr,to:1/0},url:Rr};wr={type:Ee.TEMPLATE,baseUrl:Ga,segmentTemplateUrl:Qe,initUrl:_r,totalSegmentsDurationMs:wt,segments:ti,nextSegmentBeyondManifest:Mu,timescale:at}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!ze)continue;const Cr={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[At];Cr&&Ve[Cr].push({id:Du,kind:Cr,segmentReference:wr,profiles:Nu,duration:it,bitrate:ja,mime:ze,codecs:$i,width:Ar,height:ki,fps:_u,quality:Iu})}}return{dynamic:Eu,liveAvailabilityStartTime:$u,duration:it,container:Pu,representations:Ve}},Xg=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?yr(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},Zg=({id:i,bitrate:e})=>({id:i,bitrate:e}),ey=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Fe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Fe(i,-1)},ty=({id:i,lang:e,label:t,url:r,isAuto:s})=>({id:i,url:r,isAuto:s,type:"internal",language:e,label:t}),ko=i=>"url"in i,xt=i=>i.type===Ee.TEMPLATE,ta=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class Po{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:h}){switch(this.currentSegmentLength$=new a.ValueSubject(0),this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ht,this.destroyAbortController=new Ht,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.loadByteRangeSegmentsTimeoutId=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(c){return fe(this,arguments,function*(){const f=this.representations.get(c);a.assertNonNullable(f,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${f.mime}; codecs="${f.codecs}"`),this.sourceBufferTaskQueue=new IS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,vo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield C(this.loadInit(f,"high",!0));const p=this.initData.get(f.id),v=this.segments.get(f.id),m=this.parsedInitData.get(f.id);if(a.assertNonNullable(p,"No init buffer for starting representation"),a.assertNonNullable(v,"No segments for starting representation"),!(p instanceof ArrayBuffer))return yield C(void 0);this.searchGaps(v,f),yield yield C(this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(c){return fe(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield C(void 0);this.switchingToRepresentationId=c;const f=this.representations.get(c);a.assertNonNullable(f,`No such representation ${c}`);let p=this.segments.get(c),v=this.initData.get(c);if(a.isNullable(v)||a.isNullable(p)?yield yield C(this.loadInit(f,"high",!1)):v instanceof Promise&&(yield yield C(v)),p=this.segments.get(c),a.assertNonNullable(p,"No segments for starting representation"),v=this.initData.get(c),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return yield C(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield C(this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.isLive||(p.forEach(b=>b.status=R.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(c){var f;return fe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield C(void 0);for(const y of this.representations.keys()){const T=c.find(O=>O.id===y);T&&this.representations.set(y,T);const E=this.representations.get(y);if(!E||!xt(E.segmentReference))return yield C(void 0);const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,v=this.representations.get(p);a.assertNonNullable(v);const m=this.segments.get(p);a.assertNonNullable(m,"No segments for starting representation");const b=this.initData.get(p);if(a.assertNonNullable(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield C(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield C(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(m,v),yield yield C(this.sourceBufferTaskQueue.append(b,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=d,this.isLive=!!(h!=null&&h.dynamic),this.container=r,r){case Gt.MP4:this.containerParser=ig;break;case Gt.WEBM:this.containerParser=ug;break;default:a.assertNever(r)}this.initData=new Map(s.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(c=>[c.id,c])),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 Ht,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var t,r;if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const s=this.representations.get(this.downloadingRepresentationId),n=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(s,`No such representation ${this.downloadingRepresentationId}`),!n)return;const o=n.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((t=o==null?void 0:o.time.to)!==null&&t!==void 0?t:0)-((r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:0));let l=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const f=oi(this.sourceBuffer.buffered,e),p=o?o.time.to+100:-1/0;o&&o.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&f>=o.time.to-e+100&&(l=p)}if(isFinite(this.bufferLimit)&&vo(this.sourceBuffer.buffered)>=this.bufferLimit){const c=oi(this.sourceBuffer.buffered,e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<f);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(n,s.segmentReference.type,l),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&o)if(u.includes(o))c="high";else{const f=Fe(u,0);f&&f.time.from-o.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,s,c)}(!this.preloadOnly&&!this.allInitsLoaded&&o&&o.status===R.FED&&!u.length&&oi(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const h=Fe(n,-1);h&&h.status===R.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(o===h))}searchGaps(e,t){this.gaps=[];let r=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:n.time.from+s}),r=n.time.to;a.isNonNullable(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let n=0,o=t.length-1;do s.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,s,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!xt(o.segmentReference))return;const l=o.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:R.NONE,size:void 0})),d=(r=this.segments.get(o.id))!==null&&r!==void 0?r:[],u=(n=(s=Fe(d,-1))===null||s===void 0?void 0:s.time.to)!==null&&n!==void 0?n:0,h=l==null?void 0:l.findIndex(c=>Math.floor(u)>=Math.floor(c.time.from)&&Math.floor(u)<=Math.floor(c.time.to));if(h===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,c)}else{const c=l.slice(h+1);this.segments.set(o.id,[...d,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const r of this.representations.values()){const s=r.segmentReference;if(!xt(s))return;const n=Math.round(e.segment.time.to*s.timescale/1e3).toString(10),o=Ot(s.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(r.id))!==null&&t!==void 0?t:[],d=l.find(h=>Math.floor(h.time.from)===Math.floor(e.segment.time.from));d&&(d.time.to=e.segment.time.to),!!l.find(h=>Math.floor(h.time.from)===Math.floor(e.segment.time.to))||l.push({status:R.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){const r=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){const s=e.findIndex(({status:c,time:{from:f,to:p}},v)=>{const m=f<=r&&p>=r,b=f>r||m||v===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=r+S||p<=r+S;return(c===R.NONE||c===R.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!ea(this.sourceBuffer.buffered,r))&&b&&y});if(s===-1)return[];if(t!==Ee.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<n.length&&(o<=u||l<=h);c++){const f=n[c];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===R.NONE||f.status===R.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return G(this,void 0,void 0,function*(){t.segmentReference.type===Ee.TEMPLATE?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return G(this,void 0,void 0,function*(){e.status=R.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:l,onProgress:d,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return fe(this,arguments,function*(){const h=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(c=>setTimeout(c,h)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const h=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:r,isLowLatency:this.isActiveLowLatency()});if(!h)return;const c=new DataView(h);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(c,f)}d&&s.feedingBytes&&u?yield Promise.all(u):yield this.sourceBufferTaskQueue.append(c,l),s.segment.status=R.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),ta(h)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return G(this,void 0,void 0,function*(){if(!e.length)return;for(const d of e)d.status=R.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield a.abortable(o,function(){return fe(this,arguments,function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,d),a.fromEvent(window,"online").pipe(a.once()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})}))})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(n,{range:s,onProgress:l,signal:o,priority:r}),this.failedDownloads=0}catch(d){this.abortActiveSegments(e),ta(d)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(xt(t.segmentReference))throw new Error("Representation is not byte range type");const r=t.segmentReference.url,s={from:Fe(e,0).byte.from,to:Fe(e,-1).byte.to},{signal:n}=this.downloadAbortController;return{url:r,range:s,signal:n,onProgress:(l,d)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:l,loaded:d,signal:n,onSegmentAppendFailed:()=>this.abort(),globalFrom:s?s.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!xt(t.segmentReference))throw new Error("Representation is not template type");const r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");const s=r.toString(),{signal:n}=this.downloadAbortController,o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,h)=>{if(!n.aborted)try{const c=this.onSomeTemplateDataLoaded({dataView:u,loaded:h,signal:n,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});o.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:s,signal:n,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:s,signal:n}){return G(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){s();continue}if(l.loadedBytes=r,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);h!=null&&h.byteLength&&(d.status=R.PARTIALLY_FED,l.feedingBytes+=h.byteLength,yield this.sourceBufferTaskQueue.append(h),l.fedBytes+=h.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:s,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const h of this.activeSegments){const{segment:c}=h,f=d===Ee.BYTE_RANGE,p=f?c.byte.to-c.byte.from+1:u;if(h.representationId!==t||!(!f||c.byte.from>=r&&c.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const m=f?c.byte.from-r:0,b=f?c.byte.to-r:e.byteLength,S=m<s,y=b<=s;if(c.status===R.DOWNLOADING&&S&&y){c.status=R.DOWNLOADED;const T=new DataView(e.buffer,e.byteOffset+m,p);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?this.onSegmentFullyAppended(h,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(h.loadedBytes=Math.min(p,s-m),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+m+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===p?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(c.status=R.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then($=>{if(n.aborted)o();else if($)h.fedBytes+=E.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=R.FED,ko(e.segment)&&(e.segment.size=e.fedBytes);for(const s of this.representations.values())if(s.id!==t)for(const n of(r=this.segments.get(s.id))!==null&&r!==void 0?r:[])n.status===R.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=R.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===R.PARTIALLY_FED||e.status===R.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=R.NONE),e.status=R.PARTIALLY_EJECTED):e.status=R.NONE;for(const r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=mo(()=>wa(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return G(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return fe(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>G(this,void 0,void 0,function*(){if(!l)return;const{init:d,dataView:u,segments:h}=l,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c);let f=h;this.isLive&&xt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)})).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return G(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const d=u=>{var h;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const c=ko(u)?(h=u.size)!==null&&h!==void 0?h:0:u.byte.to-u.byte.from;s+=c};for(const u of this.segments.values())for(const h of u){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===R.FED&&d(h)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const h of u){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===R.FED&&d(h)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const h=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===R.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(c)){n=h,o=c;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const c of h)c.time.from>e+u&&c.status===R.FED&&d(c)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=mo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==R.FED&&n!==R.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=l),u=e.filter(h=>o>=h.from-t&&o<=h.to+t||l>=h.from-t&&l<=h.to+t);d||(u.length===1||this.gaps.some(h=>h.from===s.time.from||h.to===s.time.to)?s.status=R.PARTIALLY_EJECTED:s.status=R.NONE)}}}var ia=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},iy=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Ut;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Ut||(Ut={}));class ry{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Ht,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return fe(this,arguments,function*(){let n=s;this.requestQuic&&(n=ia(n));const o=yield yield C(di(n,{signal:this.abortAllController.signal}).catch(ri));return o?(this.onHeadersReceived(o.headers),yield C(o.text())):yield C(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Ut.HEADER:Ut.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:h=!0,isLowLatency:c=!1}={}){var f,p;return fe(this,arguments,function*(){let v=s;const m=new Headers;if(o)switch(n){case Ut.HEADER:{m.append("Range",`bytes=${o.from}-${o.to}`);break}case Ut.PARAM:{const A=new URL(v,location.href);A.searchParams.append("bytes",`${o.from}-${o.to}`),v=A.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=ia(v));let b=this.abortAllController.signal,S;if(u){const A=new Ht;if(S=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{A.abort()}catch(W){ri(W)}}),this.abortAllController.signal.aborted||u.aborted)try{A.abort()}catch(W){ri(W)}b=A.signal}const y=a.now(),T=yield yield C(di(v,{priority:d,headers:m,signal:b}).catch(ri)),E=a.now();if(!T)return S==null||S.unsubscribe(),yield C(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(E-y),!T.ok||!T.body)return S==null||S.unsubscribe(),yield C(Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`)));if(this.onHeadersReceived(T.headers),!l&&!h)return S==null||S.unsubscribe(),yield C(T.arrayBuffer());const[$,O]=T.body.tee(),M=$.getReader();h&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(O,c));let F=0,x=new Uint8Array(0),U=!1;const H=A=>{S==null||S.unsubscribe(),U=!0,ri(A)},I=a.abortable(b,function({done:A,value:W}){return fe(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(a.now()-y),b.aborted)return S==null||S.unsubscribe(),yield C(void 0);if(!A&&W){const _=new Uint8Array(x.length+W.length);_.set(x),_.set(W,x.length),x=_,F+=W.byteLength,l==null||l(new DataView(x.buffer),F),yield yield C(M==null?void 0:M.read().then(I,H))}})}.bind(this));return yield yield C(M==null?void 0:M.read().then(I,H)),S==null||S.unsubscribe(),yield C(U?null:x.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return fe(this,arguments,function*(){if(s.type!==Ee.BYTE_RANGE)return yield C(null);const{from:d,to:u}=s.initRange;let h=d,c=u,f=!1,p,v;s.indexRange&&(p=s.indexRange.from,v=s.indexRange.to,f=u+1===p,f&&(h=Math.min(p,d),c=Math.max(v,u))),h=Math.min(h,0);const m=yield yield C(this.fetch(s.url,{range:{from:h,to:c},priority:o,measureThroughput:!1}));if(!m)return yield C(null);const b=new DataView(m,d-h,u-h+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),y=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!y)throw new ReferenceError("No way to load representation index");let T;if(f)T=new DataView(m,y.from-h,y.to-y.from+1);else{const $=yield yield C(this.fetch(s.url,{range:y,priority:o,measureThroughput:!1}));if(!$)return yield C(null);T=new DataView($)}const E=n.parseSegments(T,S,y);return yield C({init:S,dataView:new DataView(m),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return fe(this,arguments,function*(){if(s.type!==Ee.TEMPLATE)return yield C(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield C(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield C(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:R.NONE,size:void 0}));return yield C({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=iy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return G(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case Ee.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case Ee.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ri=i=>{if(!ta(i))throw i},Mt=1e3,lr=(i,e,t)=>t*e+(1-t)*i,mu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,sy=(i,e,t,r)=>{let s=0,n=t;const o=mu(i,e),l=e<r?e:r;for(let d=0;d<l;d++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class xa{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new xe(`raw_${r}`),this.smoothedSeries$=new xe(`smoothed_${r}`),this.reportedSeries$=new xe(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class ay extends xa{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=lr(this.slow,e,this.params.emaAlphaSlow),this.fast=lr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ny extends xa{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=mu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=lr(this.emaSmoothed,e,this.params.emaAlpha);const r=sy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class oy extends xa{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?lr(this.smoothed,e,this.params.emaAlpha):e}}class ra{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ay({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ny({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new oy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const ly=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},lt=()=>window.ManagedMediaSource||window.MediaSource,vu=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},uy=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cy=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,Ao=["timeupdate","progress","play","seeked","stalled","waiting"];var Te;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Te||(Te={}));let dy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new Z(Te.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.currentVideoSegmentLength$=new a.ValueSubject(0),this.currentAudioSegmentLength$=new a.ValueSubject(0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.livePositionFromPlayer$=new a.ValueSubject(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ht,this.initManifest=a.abortable(this.destroyController.signal,function(t,r,s){var n;return fe(this,arguments,function*(){this.element=t,this.manifestUrlString=Ce(r,s,re.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Te.MANIFEST_READY),this.manifest=yield yield C(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Te.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=a.abortable(this.destroyController.signal,function(){var t;return fe(this,arguments,function*(){const r=yield yield C(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!r)return yield C(null);let s;try{s=Jg(r!=null?r:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!s)return yield C(null);const n=({kind:o,mime:l,codecs:d})=>{var u,h,c,f;return!!(!((h=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||h===void 0)&&h.call(u,l)&&(!((f=(c=lt())===null||c===void 0?void 0:c.isTypeSupported)===null||f===void 0)&&f.call(c,`${l}; codecs="${d}"`))||o===ae.TEXT)};return s.dynamic&&this.isLive$.getValue()!==s.dynamic&&(this.isLive$.next(s.dynamic),this.liveDuration$.getValue()!==s.duration&&this.liveDuration$.next(-1*((t=s.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==s.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(s.liveAvailabilityStartTime)),yield C(Object.assign(Object.assign({},s),{representations:rr(Object.entries(s.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r,s){var n;return fe(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Te.REPRESENTATIOS_READY);const o=m=>{this.representationSubscription.add(a.fromEvent(m,"error").pipe(a.filter(b=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?cy():new MediaSource;const l=document.createElement("source");if(o(l),l.src=URL.createObjectURL(this.source),this.element.appendChild(l),this.tuning.useManagedMediaSource&&vu())if(s){const m=document.createElement("source");o(m),m.type="application/x-mpegurl",m.src=s.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const d={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Po(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,d),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Po(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,d),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(a.interval(Mt).subscribe(m=>{var b;if(!((b=this.element)===null||b===void 0)&&b.paused){const S=lo(this.manifestUrlString,re.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ce(this.manifestUrlString,S+Mt,re.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Ao.filter(m=>m!=="waiting").map(m=>a.fromEvent(this.element,m))).pipe(a.map(m=>this.element?oi(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(m=>!!m),a.tap(m=>{var b;(b=this.stallWatchdogSubscription)===null||b===void 0||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=b-S;let $=1+Math.sign(E)*T;Math.abs(E)<y?$=1:Math.abs(E)>y*2&&($=1+Math.sign(E)*T*2),ly(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,y;let T=0;if(b){const E=((y=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&y!==void 0?y:0)*1e3;T=Math.min(...this.bufferManagers.map(O=>{var M,F;return(F=(M=O.getLiveSegmentsToLoadState(this.manifest))===null||M===void 0?void 0:M.to)!==null&&F!==void 0?F:E}))-E}this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let m=0;this.representationSubscription.add(a.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(a.throttle(Mt)).subscribe(({liveLoadBufferLength:b,bufferLength:S})=>G(this,void 0,void 0,function*(){if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,T=lo(this.manifestUrlString,re.DASH_CMAF_OFFSET_P),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),O=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,F=this.isActiveLowLatency?S:b;let x=De.None;if(this.isActiveLowLatency?x=De.ActiveLowLatency:F<$+M&&F>=$?x=De.LiveWithTargetOffset:T!==0&&F<$&&(x=De.LiveForwardBuffering),isFinite(b)&&(m=b>m?b:m),x===De.LiveForwardBuffering||x===De.LiveWithTargetOffset){const U=m-($+O),H=this.normolizeLiveOffset(Math.trunc(T+U/y)),I=Math.abs(H-T);let A;!b||I<=this.tuning.dashCmafLive.offsetCalculationError?A=T:H>0&&I>this.tuning.dashCmafLive.offsetCalculationError?A=H:A=0,this.manifestUrlString=Ce(this.manifestUrlString,A,re.DASH_CMAF_OFFSET_P)}x!==De.None&&x!==De.ActiveLowLatency&&(m=0,this.updateLive())})))}const u=a.merge(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),h=a.merge(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:u,someBufferEnded:h}).pipe(a.filter(({allBuffersFull:m,someBufferEnded:b})=>m&&b))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield yield C(new Promise(m=>{var b;return(b=this.source)===null||b===void 0?void 0:b.addEventListener("sourceopen",m)})));const c=(n=this.manifest.duration)!==null&&n!==void 0?n:0,f=(m,b)=>{var S;return Math.max(m,(S=b.duration)!==null&&S!==void 0?S:0)},p=this.manifest.representations.audio.reduce(f,c),v=this.manifest.representations.video.reduce(f,c);(p||v)&&(this.source.duration=Math.max(p,v)/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield C(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield C(this.videoBufferManager.startWith(t)),this.state$.setState(Te.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ry({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ra.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,r,s,n;return G(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.manifestUrlString=Ce(this.manifestUrlString,o,re.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((r=this.manifest)===null||r===void 0?void 0:r.representations.video),yield(s=this.audioBufferManager)===null||s===void 0?void 0:s.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio))})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Te.RUNNING),this.subscription.add(a.merge(...Ao.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&ea(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=Mt,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=a.interval(Mt).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:a.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return G(this,void 0,void 0,function*(){const r={[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),ea(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t,r;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(s=>s.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)===null||r===void 0||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Te.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return G(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const n of this.bufferManagers)for(const o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=t&&o.to+s>t&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){const n=Math.max(...r)+10;n===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=n/1e3}}};class hy{constructor(e,t){this.fov=e,this.orientation=t}}class fy{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:s,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var py=`#define GLSLIFY 1
38
- attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,my=`#ifdef GL_ES
39
- precision highp float;precision highp int;
33
+ [best track] ${Y==null?void 0:Y.quality}
34
+ [selected track] ${j==null?void 0:j.quality}
35
+ `});let K=j&&l&&l.history[j.id]&&(0,U.now)()-l.history[j.id]<=r.trackCooldown&&(!l.last||j.id!==l.last.id);if(j!=null&&j.id&&l&&!K&&l.recordSelection(j),K&&(l!=null&&l.last)){let V=l.last;return l==null||l.recordSwitch(V),d({message:`
36
+ [last selected] ${V==null?void 0:V.quality}
37
+ `}),V}return l==null||l.recordSwitch(j),j},$t=rx;var fe=i=>new URL(i).hostname;var B=require("@vkontakte/videoplayer-shared");var mf=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},Ae=i=>_(void 0,null,function*(){let e=i.muted;try{yield i.play()}catch(t){if(!mf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return mf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});var Ce=require("@vkontakte/videoplayer-shared");var it=require("@vkontakte/videoplayer-shared");function me(){return(0,it.now)()}function Lo(i){return me()-i}function $o(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function bf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function wr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,f="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,it.assertNonNullable)(c);let D=Lo(c),te;if(D<g){te=g-D,setTimeout(S,te);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new a,Q()},y=D=>(s=D,q),v=D=>(d=D,q),E=()=>(f="json",q),x=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},P=D=>(p=D,q),Q=()=>{c=me(),n=new a,n.open("get",i);let D=0,te,ce=0,V=()=>((0,it.assertNonNullable)(c),Math.max(c,Math.max(te||0,ce||0)));if(s&&n.addEventListener("progress",A=>{let Z=me();s.updateChunk&&A.loaded>D&&(s.updateChunk(V(),A.loaded-D),D=A.loaded,te=Z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;(0,it.assertNonNullable)(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let Z=n.response.byteLength-D;Z&&s.updateChunk&&s.updateChunk(V(),Z)}n.responseType==="json"&&!Object.values(n.response).length?x():(d&&d(),e(n.response))}else x()}),n.addEventListener("error",()=>{x()}),p){let A=()=>{(0,it.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ce=me(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=f,n.send(),q},q={withBitrateReporting:y,withParallel:P,withJSONResponse:E,withRetryCount:D=>(l=D,q),withRetryInterval:(D,te)=>((0,it.isNonNullable)(D)&&(g=D),(0,it.isNonNullable)(te)&&(m=te),q),withTimeout:D=>(o=D,q),withFinally:v,send:Q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var li=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>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}};var ci=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let 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){let r=me(),a=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)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=me()-r,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=wr(t,s,()=>a("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=me()}_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(){let e=this._getParallelRequestCount(),t=me();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._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}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let 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(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}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}};var ts=1e4,Co=3;var ax=6e4,sx=10,nx=1,ox=500,di=class{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 li(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=$o(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():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=$o(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ce.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{bf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({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 ci(Co,ts,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,P,Q)=>{u&&u.abort(),u=wr(this.urlResolver.resolve(x,!1),P,Q,()=>this._retryCallback()).withTimeout(ts).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Co).withFinally(()=>{u=null}).send()},f=(x,P,Q)=>{(0,Ce.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),P,Q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=x=>{let P=r.playbackRate;r.playbackRate!==x&&(t(`Playback rate switch: ${P}=>${x}`),r.playbackRate=x)},g=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let Q=me()-1e4,Y=0;for(let K=0;K<this.bufferStates.length;K++){let re=this.bufferStates[K];x=Math.min(x,re.buf),re.ts<Q&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${x} drop=${Y} jitter=${this.sourceJitter}`);let j=x-nx;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?m(1.15):j>1?m(1.1):j>.3?m(1.05):m(1)}},y=x=>{let P,Q=()=>P&&P.start?P.start.length:0,Y=A=>P.start[A]/1e3,j=A=>P.dur[A]/1e3,K=A=>P.fragIndex+A,re=(A,Z)=>({chunkIdx:K(A),startTS:Y(A),dur:j(A),discontinuity:Z}),q=()=>{let A=0;if(P&&P.dur){let Z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,de=Z;this.sourceJitter>1&&(de+=this.sourceJitter-1);let ve=P.dur.length-1;for(;ve>=0&&(de-=P.dur[ve],!(de<=0));--ve);A=Math.min(ve,P.dur.length-1-oe),A=Math.max(A,0)}return re(A,!0)},D=A=>{let Z=Q();if(!(Z<=0)){if((0,Ce.isNonNullable)(A)){for(let oe=0;oe<Z;oe++)if(Y(oe)>A)return re(oe)}return q()}},te=A=>{let Z=Q(),oe=A?A.chunkIdx+1:0,de=oe-P.fragIndex;if(!(Z<=0)){if(!A||de<0||de-Z>sx)return t(`Resync: offset=${de} bChunks=${Z} chunk=`+JSON.stringify(A)),q();if(!(de>=Z))return re(oe-P.fragIndex,!1)}},ce=(A,Z,oe)=>{l&&l.abort(),l=wr(this.urlResolver.resolve(A,!0,this.lowLatency),Z,oe,()=>this._retryCallback()).withTimeout(ts).withRetryCount(Co).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,Z)=>{ce(x,oe=>{if(!d())return;P=oe;let de=!!P.lowLatency;de!==this.lowLatency&&g(de);let ve=0;for(let nt=0;nt<P.dur.length;++nt)ve+=P.dur[nt];ve>0&&((0,Ce.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/P.dur.length)),a({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,A(D(Z))},()=>this._handleNetworkError())},nextChunk:te}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ce.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:P,logger:Q}=this.params,Y=y(e.jidxUrl),j,K,re,q,D=0,te,ce,V,A=()=>{te&&(clearTimeout(te),te=void 0);let J=Math.max(ox,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=D+J,Re=me(),De=Math.min(1e4,ye-Re);D=Re;let It=()=>{l||d()&&Y.seek(()=>{d()&&(D=me(),Z(),A())})};De>0?te=window.setTimeout(()=>{this.paused?A():It()},De):It()},Z=()=>{let J;for(;J=Y.nextChunk(q);)q=J,ea(J);let ye=Y.nextChunk(re);if(ye){if(re&&ye.discontinuity){Q("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}nt(ye)}else A()},oe=(J,ye)=>{if(!d()||!this.sourceBuffer)return;let Re,De,It,nr=Et=>{window.setTimeout(()=>{d()&&oe(J,ye)},Et)};if(this.sourceBuffer.updating)Q("Source buffer is updating; delaying appendBuffer"),nr(100);else{let Et=me(),Ot=P.currentTime;!this.paused&&P.buffered.length>1&&ce===Ot&&Et-V>500&&(Q("Stall suspected; trying to fix"),this._fixupStall()),ce!==Ot&&(ce=Ot,V=Et);let or=this._getBufferSizeSec();if(or>30)Q(`Buffered ${or} seconds; delaying appendBuffer`),nr(2e3);else try{this.sourceBuffer.appendBuffer(J),this.videoPlayStarted?(this.bufferStates.push({ts:Et,buf:or}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(Br){if(Br.name==="QuotaExceededError")Q("QuotaExceededError; delaying appendBuffer"),It=this.sourceBuffer.buffered.length,It!==0&&(Re=this.sourceBuffer.buffered.start(0),De=Ot,De-Re>4&&this.sourceBuffer.remove(Re,De-3)),nr(1e3);else throw Br}}},de=()=>{K&&j&&(Q([`Appending chunk, sz=${K.byteLength}:`,JSON.stringify(re)]),oe(K,function(){K=null,Z()}))},ve=J=>e.fragUrlTemplate.replace("%%id%%",J.chunkIdx),nt=J=>{d()&&f(ve(J),(ye,Re)=>{if(d()){if(Re/=1e3,K=ye,re=J,n=J.startTS,Re){let De=Math.min(10,J.dur/Re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}de()}},()=>this._handleNetworkError())},ea=J=>{d()&&((0,Ce.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(J),!1)))},Or=J=>{d()&&(e.cachedHeader=J,oe(J,()=>{j=!0,de()}))};s=!0,Y.seek(J=>{if(d()){if(D=me(),!J){A();return}q=J,!(0,Ce.isNullable)(x)||J.startTS>x?nt(J):(re=J,Z())}},x),e.cachedHeader?Or(e.cachedHeader):p(e.headerUrl,Or,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Ce.isNonNullable)(a)&&(a+=.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,(0,Ce.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ce.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(f=this._getBufferSizeSec(),m=d/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,f)=>{let m=me();if(this.chunkRateEstimator.addInterval(p,m,f)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Lo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let f=s.updateChunk(d,p);return f&&l(),f},notifySwitch:d=>{let p=me();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=wr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ts).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ae(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ax))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ne=require("@vkontakte/videoplayer-shared"),Do=class{constructor(){this.onDroopedVideoFramesLimit$=new ne.Subject;this.subscription=new ne.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ne.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ne.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ne.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ne.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ne.interval)(this.droppedFramesChecker.checkTime).pipe((0,ne.filter)(()=>this.playing),(0,ne.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ne.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ne.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ne.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},rs=Do;var is=require("@vkontakte/videoplayer-shared"),gf=require("@vkontakte/videoplayer-shared");var pi=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var ux=(i,e)=>new is.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||pi()))},M(M({},r),e));a.observe(i);let s=(0,gf.fromEvent)(document,"visibilitychange").pipe((0,is.map)(n=>!document.hidden||pi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),_e=ux;var lx=["paused","playing","ready"],cx=["paused","playing","ready"],hi=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new G("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new Ve;this.droppedFramesManager=new rs;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new dt;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:B.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Lt(u.name))!=null?r:(0,B.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=M({},u.video);if(!c)continue;let f={id:l,quality:c,bitrate:d,size:p};o.push({track:f,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,B.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(cx.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&lx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a==null?void 0:a.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ge(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=xe(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.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ke(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe((0,B.map)(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,B.filterChanged)(),(0,B.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(we(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(_e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,B.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,B.assertNever)(a.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}createLiveDashPlayer(){let e=new di({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,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,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,f,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&(0,B.isNonNullable)(t)?t:$t(e.map(({track:g})=>g),{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(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(f=this.params.desiredState.videoTrack.getState())==null?void 0:f.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,B.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;(0,B.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.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();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ge(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var vf=hi;var Ct=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var C=require("@vkontakte/videoplayer-shared");var as=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];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}},kr=class extends as{constructor(){super(),this.listeners||as.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)}},fi=class{constructor(){Object.defineProperty(this,"signal",{value:new kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(fi.prototype[Symbol.toStringTag]="AbortController",kr.prototype[Symbol.toStringTag]="AbortSignal");function ss(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Mo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ss({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(f){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((f,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var mi=ss({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Sf=mi?Mo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ft=mi?Sf.fetch:window.fetch,GL=mi?Sf.Request:window.Request,mt=mi?fi:window.AbortController,YL=mi?kr:window.AbortSignal;var vm=He(Na(),1);var bi=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared");var Cr=He(Za(),1);var dx=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},px=i=>window.clearTimeout(i),yf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Oo=yf?dx:window.requestIdleCallback,zL=yf?px:window.cancelIdleCallback;var dm=He(Ja(),1);var Ne=require("@vkontakte/videoplayer-shared");var hx=16,Ef=!1,Tf,If;try{Ef=(0,Ne.getCurrentBrowser)().browser===Ne.CurrentClientBrowser.Safari&&parseInt((If=(Tf=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Tf[1])!=null?If:"",10)<=hx}catch(i){console.error(i)}var Bo=class{constructor(e){this.bufferFull$=new Ne.Subject;this.error$=new Ne.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ne.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return _(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})})}remove(e,t,r){return _(this,null,function*(){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})})}abort(e){return _(this,null,function*(){return new Promise(t=>{let r;Ef&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ne.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{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:(0,Ne.assertNever)(t)}}},xf=Bo;var Vo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var w=require("@vkontakte/videoplayer-shared");var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Ar=class extends X{};var gi=class extends X{};var vi=class extends X{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var Si=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends X{constructor(t,r){super(t,r);this.data=this.content}};var ue=class extends X{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Qt=class extends ue{constructor(t,r){super(t,r);this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,u=this.readUint32();s=this.readUint32();let l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:u,SAPType:l,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Ii=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends ue{constructor(t,r){super(t,r);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Pi=class extends ue{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var wi=class extends ue{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ki=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends ue{constructor(t,r){super(t,r);this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ri=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends ue{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Ci=class extends X{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends ue{constructor(t,r){super(t,r);this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Mi=class extends ue{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Oi=class extends ue{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var mx={ftyp:vi,moov:Si,moof:yi,mdat:Ti,sidx:Qt,trak:Ii,mdia:ki,mfhd:$i,tkhd:Ai,traf:Ci,tfhd:Di,tfdt:Mi,trun:Oi,minf:Ri,sv3d:Ei,st3d:xi,prhd:Pi,proj:Li,equi:wi,uuid:gi,unknown:Ar},zt=class i{constructor(e={}){this.options=M({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(a){break}return t}createBox(e,t){let r=mx[e];return r?new r(t,new i):new Ar(t,new i)}};var Rr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var gx=new TextDecoder("ascii"),vx=i=>gx.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Sx=i=>{let e=new Qt(i,new zt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},yx=(i,e)=>{let r=new zt().parse(i),a=new Rr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},Tx=(i,e)=>{let r=new zt().parse(i),s=new Rr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Ix=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new zt().parse(i),a=new Rr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Pf={validateData:vx,parseInit:Ix,getIndexRange:()=>{},parseSegments:Sx,parseFeedableSegmentChunk:yx,getSegmentEndTime:Tx};var bt=require("@vkontakte/videoplayer-shared");var kf=require("@vkontakte/videoplayer-shared");var wf={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Af=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Bi(i,t),a=r in wf,s=a?wf[r].type:"binary",n=i.getUint8(t),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);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=Bi(u),d=l*Xe(2,(o-1)*8)+c,p=t+o,f;return p+d>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:f,valueSize:d}},Bi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Xe(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Xe(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Xe(2,32)+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Bi(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:(0,kf.assertNever)(e)}},Kt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Af(r);if(!e(a))return;a.type==="master"&&Kt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Rf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Af(i);return Kt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(r=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Lf=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ex=[231,22612,22743,167,171,163,160,175],xx=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Kt(i,({tag:p,type:f,value:m,valueSize:g})=>{if(p===21419){let S=ze(m,f);l=Bi(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ze(m,f):p===17545?a=ze(m,f):p===21420&&l===475249515?u=ze(m,f):p===374648427?Kt(m,({tag:S,type:y,value:v})=>S===30321?(c=ze(v,y)===1,!1):!0):s&&n&&Lf.includes(p)&&(o=!0),!o}),(0,bt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,bt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,bt.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Px=i=>{if((0,bt.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wx=(i,e)=>{let t=!1,r=!1,a=o=>(0,bt.isNonNullable)(o.time)&&(0,bt.isNonNullable)(o.position),s=[],n;return Kt(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=ze(l,u));break;case 183:break;case 241:n&&(n.position=ze(l,u));break;default:t&&Lf.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},kx=i=>{let e=0,t=!1;try{Kt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Ex.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},$f={validateData:Rf,parseInit:xx,getIndexRange:Px,parseSegments:wx,parseFeedableSegmentChunk:kx};var Ho=He(tm(),1),$r=require("@vkontakte/videoplayer-shared");var rm=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var im=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Jt=(i,e)=>{let t=i;t=(0,Ho.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ho.default)(t,n,(o,u)=>(0,$r.isNullable)(s)?o:(0,$r.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sm=(i,e)=>{var x,P,Q,Y,j,K,re,q,D,te,ce,V,A,Z,oe,de,ve,nt,ea,Or,J,ye,Re,De,It,nr,Et,Ot,or,Br,tu,ru,iu,au,su,nu,ou,uu,lu,cu,du,pu;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(Q=(P=(x=s.querySelector("BaseURL"))==null?void 0:x.textContent)==null?void 0:P.trim())!=null?Q:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=im(f);else if(m){let Me=im(m);(0,$r.isNonNullable)(Me)&&(p=Me)}else S&&(p=parseInt(S,10));let y=0,v=(j=(Y=s.getAttribute("profiles"))==null?void 0:Y.split(","))!=null?j:[],E=v.includes("urn:webm:dash:profile:webm-on-demand:2012")||v.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let Me of u){let ta=Me.getAttribute("mimeType"),rb=Me.getAttribute("codecs"),hu=(K=Me.getAttribute("contentType"))!=null?K:ta==null?void 0:ta.split("/")[0],ib=(q=(re=Me.getAttribute("profiles"))==null?void 0:re.split(","))!=null?q:[],fu=Me.querySelectorAll("Representation"),ab=Me.querySelector("SegmentTemplate");if(hu==="text"){for(let le of fu){let xt=le.getAttribute("id")||"",ra=Me.getAttribute("lang"),ur=Me.getAttribute("label"),Ps=(ce=(te=(D=le.querySelector("BaseURL"))==null?void 0:D.textContent)==null?void 0:te.trim())!=null?ce:"",ws=new URL(Ps||o,e).toString(),ia=xt.includes("_auto");a.text.push({id:xt,lang:ra,label:ur,isAuto:ia,kind:"text",url:ws})}continue}for(let le of fu){let xt=(V=le.getAttribute("mimeType"))!=null?V:ta,ra=(Z=(A=le.getAttribute("codecs"))!=null?A:rb)!=null?Z:"",ur=(de=(oe=le.getAttribute("contentType"))!=null?oe:xt==null?void 0:xt.split("/")[0])!=null?de:hu,Ps=(nt=(ve=Me.getAttribute("profiles"))==null?void 0:ve.split(","))!=null?nt:[],ws=parseInt((ea=le.getAttribute("width"))!=null?ea:"",10),ia=parseInt((Or=le.getAttribute("height"))!=null?Or:"",10),mu=parseInt((J=le.getAttribute("bandwidth"))!=null?J:"",10)/1e3,bu=(ye=le.getAttribute("frameRate"))!=null?ye:"",sb=(Re=le.getAttribute("quality"))!=null?Re:void 0,nb=bu?rm(bu):void 0,ob=(De=le.getAttribute("id"))!=null?De:(y++).toString(10),ub=ur==="video"?`${ia}p`:ur==="audio"?`${mu}Kbps`:ra,lb=`${ob}@${ub}`,cb=(Et=(nr=(It=le.querySelector("BaseURL"))==null?void 0:It.textContent)==null?void 0:nr.trim())!=null?Et:"",gu=new URL(cb||o,e).toString(),db=[...v,...ib,...Ps],ks,pb=le.querySelector("SegmentBase"),Bt=(Ot=le.querySelector("SegmentTemplate"))!=null?Ot:ab;if(pb){let Vt=(Br=(or=le.querySelector("SegmentBase Initialization"))==null?void 0:or.getAttribute("range"))!=null?Br:"",[_t,Rs]=Vt.split("-").map(lr=>parseInt(lr,10)),Pt={from:_t,to:Rs},Vr=(tu=le.querySelector("SegmentBase"))==null?void 0:tu.getAttribute("indexRange"),[Ls,aa]=Vr?Vr.split("-").map(lr=>parseInt(lr,10)):[],_r=Vr?{from:Ls,to:aa}:void 0;ks={type:"byteRange",url:gu,initRange:Pt,indexRange:_r}}else if(Bt){let Vt={representationId:(ru=le.getAttribute("id"))!=null?ru:void 0,bandwidth:(iu=le.getAttribute("bandwidth"))!=null?iu:void 0},_t=parseInt((au=Bt.getAttribute("timescale"))!=null?au:"",10),Rs=(su=Bt.getAttribute("initialization"))!=null?su:"",Pt=Bt.getAttribute("media"),Vr=(ou=parseInt((nu=Bt.getAttribute("startNumber"))!=null?nu:"",10))!=null?ou:1,Ls=Jt(Rs,Vt);if(!Pt)throw new ReferenceError("No media attribute in SegmentTemplate");let aa=(uu=Bt.querySelectorAll("SegmentTimeline S"))!=null?uu:[],_r=[],lr=0,$s="",Cs=0;if(aa.length){let sa=Vr,Ue=0;for(let cr of aa){let Je=parseInt((lu=cr.getAttribute("d"))!=null?lu:"",10),Nt=parseInt((cu=cr.getAttribute("r"))!=null?cu:"",10)||0,na=parseInt((du=cr.getAttribute("t"))!=null?du:"",10);Ue=Number.isFinite(na)?na:Ue;let Ds=Je/_t*1e3,Ms=Ue/_t*1e3;for(let oa=0;oa<Nt+1;oa++){let fb=Jt(Pt,z(M({},Vt),{segmentNumber:sa.toString(10),segmentTime:(Ue+oa*Je).toString(10)})),vu=(Ms!=null?Ms:0)+oa*Ds,mb=vu+Ds;sa++,_r.push({time:{from:vu,to:mb},url:fb})}Ue+=(Nt+1)*Je,lr+=(Nt+1)*Ds}Cs=Ue/_t*1e3,$s=Jt(Pt,z(M({},Vt),{segmentNumber:sa.toString(10),segmentTime:Ue.toString(10)}))}else if((0,$r.isNonNullable)(p)){let Ue=parseInt((pu=Bt.getAttribute("duration"))!=null?pu:"",10)/_t*1e3,cr=Math.ceil(p/Ue),Je=0;for(let Nt=1;Nt<cr;Nt++){let na=Jt(Pt,z(M({},Vt),{segmentNumber:Nt.toString(10),segmentTime:Je.toString(10)}));_r.push({time:{from:Je,to:Je+Ue},url:na}),Je+=Ue}Cs=Je,$s=Jt(Pt,z(M({},Vt),{segmentNumber:cr.toString(10),segmentTime:Je.toString(10)}))}let hb={time:{from:Cs,to:1/0},url:$s};ks={type:"template",baseUrl:gu,segmentTemplateUrl:Pt,initUrl:Ls,totalSegmentsDurationMs:lr,segments:_r,nextSegmentBeyondManifest:hb,timescale:_t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ur||!xt)continue;let As={video:"video",audio:"audio",text:"text"}[ur];As&&a[As].push({id:lb,kind:As,segmentReference:ks,profiles:db,duration:p,bitrate:mu,mime:xt,codecs:ra,width:ws,height:ia,fps:nb,quality:sb})}}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,container:E,representations:a}};var Go=He(Za(),1);var nm=require("@vkontakte/videoplayer-shared"),om=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?Lt(s):void 0)!=null?o:(0,nm.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},um=({id:i,bitrate:e})=>({id:i,bitrate:e}),lm=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,Go.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,Go.default)(i,-1)},cm=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),Yo=i=>"url"in i,Xt=i=>i.type==="template",Vi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var _i=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:c}){this.currentSegmentLength$=new w.ValueSubject(0);this.onLastSegment$=new w.ValueSubject(!1);this.fullyBuffered$=new w.ValueSubject(!1);this.playingRepresentation$=new w.ValueSubject(void 0);this.playingRepresentationInit$=new w.ValueSubject(void 0);this.error$=new w.Subject;this.gaps=[];this.subscription=new w.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new mt;this.destroyAbortController=new mt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,w.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){let t=this.representations.get(e);(0,w.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xf(this.sourceBuffer),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:w.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,Vo(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,w.assertNonNullable)(r,"No init buffer for starting representation"),(0,w.assertNonNullable)(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,w.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,w.assertNonNullable)(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,w.isNullable)(a)||(0,w.isNullable)(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();(0,w.isNonNullable)(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))})}.bind(this));this.seekLive=(0,w.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let l=e.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Xt(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,r=this.representations.get(t);(0,w.assertNonNullable)(r);let a=this.segments.get(t);(0,w.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(t);if((0,w.assertNonNullable)(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=Pf;break;case"webm":this.containerParser=$f;break;default:(0,w.assertNever)(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new mt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,w.isNullable)(e)||(0,w.isNullable)(this.downloadingRepresentationId)||(0,w.isNullable)(this.playingRepresentationId)||(0,w.isNullable)(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,w.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=a==null?void 0:a.time.to)!=null?l:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ct(this.sourceBuffer.buffered,e),f=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=f)}if(isFinite(this.bufferLimit)&&Vo(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ct(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,Cr.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&Ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Cr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;(0,w.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!Xt(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>z(M({},d),{status:"none",size:void 0})),u=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=(0,Cr.default)(u,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(l)>=Math.floor(d.time.from)&&Math.floor(l)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...u,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!Xt(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Jt(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:f}},m)=>{let g=p<=r&&f>=r,S=p>r||g||m===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=r+y||f<=r+y;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&!bi(this.sourceBuffer.buffered,r))&&S&&v});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return _(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return _(this,null,function*(){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,w.abortable)(o,function(){return pe(this,null,function*(){let c=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}u&&a.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Vi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return _(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,w.abortable)(n,function(){return pe(this,null,function*(){let u=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,w.fromEvent)(window,"online").pipe((0,w.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Vi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Xt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Cr.default)(e,0).byte.from,to:(0,Cr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Xt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return _(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){a();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",f=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,y=g<a,v=S<=a;if(d.status==="downloading"&&y&&v){d.status="downloaded";let E=new DataView(e.buffer,e.byteOffset+g,f);this.sourceBufferTaskQueue.append(E,s).then(x=>x&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(c.loadedBytes=Math.min(f,a-g),c.loadedBytes>c.feedingBytes)){let E=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),x=c.loadedBytes===f?E:this.containerParser.parseFeedableSegmentChunk(E);x!=null&&x.byteLength&&(d.status="partially_fed",c.feedingBytes+=x.byteLength,this.sourceBufferTaskQueue.append(x,s).then(P=>{if(s.aborted)n();else if(P)c.fedBytes+=x.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Yo(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Oo(()=>(0,dm.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return _(this,null,function*(){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,w.abortable)(this.destroyAbortController.signal,function(){return pe(this,null,function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(o=>_(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Xt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:w.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,r=!1){return _(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,w.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Yo(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;a+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Oo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:w.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,w.isNullable)(this.sourceBuffer)||(0,w.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ni=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var pm=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};var ie=require("@vkontakte/videoplayer-shared");var ns=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new ie.ValueSubject(void 0);this.lastConnectionReused$=new ie.ValueSubject(void 0);this.lastRequestFirstBytes$=new ie.ValueSubject(void 0);this.abortAllController=new mt;this.subscription=new ie.Subscription;this.fetchManifest=(0,ie.abortable)(this.abortAllController.signal,function(e){return pe(this,null,function*(){let t=e;this.requestQuic&&(t=Ni(t));let r=yield ft(t,{signal:this.abortAllController.signal}).catch(Fi);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=(0,ie.abortable)(this.abortAllController.signal,function(l){return pe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var K,re;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let q=new URL(c,location.href);q.searchParams.append("bytes",`${r.from}-${r.to}`),c=q.toString();break}default:(0,ie.assertNever)(t)}this.requestQuic&&(c=Ni(c));let p=this.abortAllController.signal,f;if(n){let q=new mt;if(f=(0,ie.merge)((0,ie.fromEvent)(this.abortAllController.signal,"abort"),(0,ie.fromEvent)(n,"abort")).subscribe(()=>{try{q.abort()}catch(D){Fi(D)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(D){Fi(D)}p=q.signal}let m=(0,ie.now)(),g=yield ft(c,{priority:s,headers:d,signal:p}).catch(Fi),S=(0,ie.now)();if(!g)return f==null||f.unsubscribe(),null;if((K=this.throughputEstimator)==null||K.addRawRtt(S-m),!g.ok||!g.body)return f==null||f.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!a&&!o)return f==null||f.unsubscribe(),g.arrayBuffer();let[y,v]=g.body.tee(),E=y.getReader();o&&((re=this.throughputEstimator)==null||re.trackStream(v,u));let x=0,P=new Uint8Array(0),Q=!1,Y=q=>{f==null||f.unsubscribe(),Q=!0,Fi(q)},j=(0,ie.abortable)(p,function(te){return pe(this,arguments,function*({done:q,value:D}){if(x===0&&this.lastRequestFirstBytes$.next((0,ie.now)()-m),p.aborted){f==null||f.unsubscribe();return}if(!q&&D){let ce=new Uint8Array(P.length+D.length);ce.set(P),ce.set(D,P.length),P=ce,x+=D.byteLength,a==null||a(new DataView(P.buffer),x),yield E==null?void 0:E.read().then(j,Y)}})}.bind(this));return yield E==null?void 0:E.read().then(j,Y),f==null||f.unsubscribe(),Q?null:P.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t,r){return pe(this,null,function*(){var y;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let f=t.parseInit(p),m=(y=e.indexRange)!=null?y:t.getIndexRange(f);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;g=new DataView(v)}let S=t.parseSegments(g,f,m);return{init:f,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t){return pe(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>z(M({},n),{status:"none",size:void 0})),dataView:new DataView(a)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=pm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return _(this,null,function*(){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,ie.assertNever)(a)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Fi=i=>{if(!Vi(i))throw i};var Zt=(i,e,t)=>t*e+(1-t)*i,Wo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,hm=(i,e,t,r)=>{let a=0,s=t,n=Wo(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var qi=require("@vkontakte/videoplayer-shared");var Dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new qi.ValueSubject(e.initial),this.debounced$=new qi.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Se(`raw_${t}`),this.smoothedSeries$=new Se(`smoothed_${t}`),this.reportedSeries$=new Se(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Xe(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,qi.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var os=class extends Dt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Zt(this.slow,t,this.params.emaAlphaSlow),this.fast=Zt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var us=class extends Dt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Wo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,t,this.params.emaAlpha);let a=hm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var ls=class extends Dt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Zt(this.smoothed,t,this.params.emaAlpha):t}};var er=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new os({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new us({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ls(M({initial:e,label:"liveEdgeDelay"},t))}};var fm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var gt=()=>window.ManagedMediaSource||window.MediaSource,cs=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},mm=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},bm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var gm=["timeupdate","progress","play","seeked","stalled","waiting"];var ds=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new T.Subscription;this.representationSubscription=new T.Subscription;this.state$=new G("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.isLive$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new mt;this.initManifest=(0,T.abortable)(this.destroyController.signal,function(e,t,r){return pe(this,null,function*(){var a;this.element=e,this.manifestUrlString=ge(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,function(){return pe(this,null,function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=sm(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var u,l,c,d;return!!((l=(u=this.element)==null?void 0:u.canPlayType)!=null&&l.call(u,n)&&((d=(c=gt())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),z(M({},t),{representations:(0,vm.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))})})}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,function(e,t,r){return pe(this,null,function*(){var f;(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=m=>{this.representationSubscription.add((0,T.fromEvent)(m,"error").pipe((0,T.filter)(g=>{var S;return!!((S=this.element)!=null&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?bm():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cs())if(r){let m=document.createElement("source");a(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new _i("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)&&(this.audioBufferManager=new _i("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.interval)(1e3).subscribe(m=>{var g;if((g=this.element)!=null&&g.paused){let S=Eo(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,S+1e3,2)}})),this.representationSubscription.add((0,T.merge)(...gm.filter(m=>m!=="waiting").map(m=>(0,T.fromEvent)(this.element,m))).pipe((0,T.map)(m=>this.element?Ct(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.filter)(m=>!!m),(0,T.tap)(m=>{var g;(g=this.stallWatchdogSubscription)==null||g.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe((0,T.filter)(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=g-S,x=1+Math.sign(E)*v;Math.abs(E)<y?x=1:Math.abs(E)>y*2&&(x=1+Math.sign(E)*v*2),fm(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var y,v;let S=0;if(g){let E=((v=(y=this.element)==null?void 0:y.currentTime)!=null?v:0)*1e3;S=Math.min(...this.bufferManagers.map(P=>{var Q,Y;return(Y=(Q=P.getLiveSegmentsToLoadState(this.manifest))==null?void 0:Q.to)!=null?Y:E}))-E}this.liveLoadBufferLength$.getValue()!==S&&this.liveLoadBufferLength$.next(S)}));let m=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(y=>_(this,[y],function*({liveLoadBufferLength:g,bufferLength:S}){if((0,T.assertNonNullable)(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,E=Eo(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),Q=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,Y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,j=this.isActiveLowLatency?S:g,K=3;if(this.isActiveLowLatency?K=0:j<P+Y&&j>=P?K=1:E!==0&&j<P&&(K=2),isFinite(g)&&(m=g>m?g:m),K===2||K===1){let re=m-(P+Q),q=this.normolizeLiveOffset(Math.trunc(E+re/v)),D=Math.abs(q-E),te;!g||D<=this.tuning.dashCmafLive.offsetCalculationError?te=E:q>0&&D>this.tuning.dashCmafLive.offsetCalculationError?te=q:te=0,this.manifestUrlString=ge(this.manifestUrlString,te,2)}K!==3&&K!==0&&(m=0,this.updateLive())})))}let o=(0,T.merge)(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),u=(0,T.merge)(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add((0,T.merge)(this.forceEnded$,(0,T.combine)({allBuffersFull:o,someBufferEnded:u}).pipe((0,T.filter)(({allBuffersFull:m,someBufferEnded:g})=>m&&g))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(m=this.source)==null||m.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(m=>{var g;return(g=this.source)==null?void 0:g.addEventListener("sourceopen",m)}));let l=(f=this.manifest.duration)!=null?f:0,c=(m,g)=>{var S;return Math.max(m,(S=g.duration)!=null?S:0)},d=this.manifest.representations.audio.reduce(c,l),p=this.manifest.representations.video.reduce(c,l);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ns({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=er.getLiveEstimatedDelaySmoothedValue(0,M({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return _(this,null,function*(){var r,a,s,n;(0,T.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=ge(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio))})}initBuffer(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...gm.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&bi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return _(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var a,s,n,o,u;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),bi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return _(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var ps=class{constructor(e,t){this.fov=e,this.orientation=t}};var hs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Xe(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=M({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*Xe(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Sm=`attribute vec2 a_vertex;
38
+ attribute vec2 a_texel;
39
+
40
+ varying vec2 v_texel;
41
+
42
+ void main(void) {
43
+ // direct vertex drawing
44
+ gl_Position = vec4(a_vertex, 0.0, 1.0);
45
+ // save texel vector to pass to fragment shader
46
+ v_texel = a_texel;
47
+ }
48
+ `;var ym=`#ifdef GL_ES
49
+ precision highp float;
50
+ precision highp int;
40
51
  #else
41
- precision highp float;
42
- #define GLSLIFY 1
52
+ precision highp float;
43
53
  #endif
54
+
44
55
  #define PI 3.14159265358979323846264
45
- varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class vy{constructor(e,t,r){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new hy(this.params.fov,this.params.orientation),this.cameraRotationManager=new fy(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(py,this.gl.VERTEX_SHADER),r=this.createShader(my,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:r=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,n=e-r,o=t-s,l=e+r,d=t-s,u=e+r,h=t+s,c=e-r,f=t+s;return[n,o,l,d,u,h,c,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class bu{constructor(e){this.subscription=new a.Subscription,this.videoState=new Z(K.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new tt,this.droppedFramesManager=new su,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new uS,this.textTracks=[],this.syncPlayback=()=>{var t,r,s;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===N.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==K.STOPPED&&o!==exports.PlaybackState.STOPPED){const h=(r=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&r!==void 0?r:0;this.seek(d.position-h,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.player.stop(),this.video.removeAttribute("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(K.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case K.STOPPED:this.videoState.startTransitionTo(K.READY),this.prepare();return;case K.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case K.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),(s=this.liveOffset)===null||s===void 0||s.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var r,s,n;if(this.scene3D)return;this.scene3D=new vy(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=t.projectionData)===null||r===void 0?void 0:r.pose.yaw)||0,y:((s=t.projectionData)===null||s===void 0?void 0:s.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new dy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,r=Tt(this.video),s=this.constructor.name,n=l=>{e.error$.next({id:s,category:a.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:h})=>h)))}),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ti(this.video,t.isLooped,s)),this.subscription.add(yt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,s)),n(a.observeElementSize(this.video),this.elementSize$),n(Kt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var h;if(u===Te.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((S,y)=>y.bitrate-S.bitrate),v=Array.from(f.video).sort((S,y)=>y.bitrate-S.bitrate),m=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const S of p){const y=Zg(S);y&&this.audioTracks.push({track:y,representation:S})}for(const S of v){const y=Xg(S);if(y){c.push({track:y,representation:S});const T=!this.params.tuning.isAudioDisabled&&ey(p,v,S);T&&this.audioRepresentations.set(S.id,T)}}this.videoTracks$.next(c);for(const S of m){const y=ty(S);y&&this.textTracks.push({track:y,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const b=this.selectVideoRepresentation();a.assertNonNullable(b),this.player.initRepresentations(b.id,(h=this.audioRepresentations.get(b.id))===null||h===void 0?void 0:h.id,this.params.sourceHls)}else u===Te.REPRESENTATIOS_READY&&(this.videoState.setState(K.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),h=this.player.state$.getTransition();if(u!==Te.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);const p=this.params.desiredState.autoVideoTrackSwitching.getState(),v=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.params.output.elementVisible$.getValue()&&p&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,y)=>y.bitrate-S.bitrate).filter(S=>{const y=a.videoSizeToQuality(S),T=a.videoSizeToQuality(c);if(y&&T)return a.isLowerOrEqual(y,T)&&a.isLowerOrEqual(y,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(ae.VIDEO,m).catch(o);const b=this.audioRepresentations.get(c.id);b&&this.player.switchRepresentation(ae.AUDIO,b.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var h;return u&&((h=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u))===null||h===void 0?void 0:h.track)})).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var h,c;if(u!=null&&u.is3dVideo&&(!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},s)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,s)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,h=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),f=oi(this.video.buffered,this.video.currentTime*1e3),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(h&&!d&&(s=(r=this.audioRepresentations.get(h.id))===null||r===void 0?void 0:r.bitrate)!==null&&s!==void 0?s:0,c&&(o=(n=this.audioRepresentations.get(c.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),b=Tr(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:v,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=d?b!=null?b:h:h!=null?h:b;return S&&((l=this.videoTracks$.getValue().find(({track:y})=>y===S))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Et(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),gt(this.video)}}class by extends bu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Sy extends bu{constructor(e){super(e),this.liveOffset=new Ia}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(Mt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()===K.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(s-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===K.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,s)})}}const Ae={};var B;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const Nt=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class gy{constructor(e){this.subscription=new a.Subscription,this.videoState=new Z(B.INITIALIZING),this.textTracksManager=new tt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==B.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case B.STOPPED:break;case B.READY:case B.PLAYING:case B.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case B.STOPPED:this.prepare();break;case B.READY:case B.PLAYING:case B.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case B.PLAYING:break;case B.STOPPED:this.prepare();break;case B.READY:case B.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case B.PAUSED:break;case B.STOPPED:this.prepare();break;case B.READY:this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case B.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=St(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Me(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.params.output.element$.next(void 0),gt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);wa(import("hls.js").then(s=>{e||(Ae.Hls=s.default,Ae.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Ae.Hls,"hls.js not loaded"),this.hls=new Ae.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(B.STOPPED)}subscribe(){a.assertNonNullable(Ae.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=Tt(this.video),n=(u,h)=>this.subscription.add(u.subscribe(h,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(Ti(this.video,e.isLooped,r)),this.subscription.add(yt(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(this.video,e.playbackRate,s.playbackRateState$,r)),n(Kt(this.video),t.elementVisible$),this.subscription.add(Nt(this.hls,Ae.Events.ERROR).subscribe(u=>{var h;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(h=u.err)===null||h===void 0?void 0:h.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===B.READY&&this.videoState.setState(B.READY),this.videoState.getState()===B.PLAYING&&this.playIfAllowed()},r)),n(Nt(this.hls,Ae.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((h,c)=>{var f,p;const v=c.name||c.height.toString(10),{width:m,height:b}=c,S=(p=yr((f=c.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:m,height:b});if(!S)return h;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,T={id:v.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:b},fps:y};return this.trackLevels.set(v,{track:T,level:c}),h.push(T),h},[]))),t.availableVideoTracks$),n(Nt(this.hls,Ae.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const h=[];for(const c of u.subtitleTracks){const f=c.name,p=c.attrs.URI||"",v=c.lang,m="internal";h.push({id:f,url:p,language:v,type:m})}e.internalTextTracks.startTransitionTo(h)}}),n(Nt(this.hls,Ae.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>Me(u))),t.hostname$),n(Nt(this.hls,Ae.Events.FRAG_CHANGED),u=>{var h,c,f,p;const{video:v,audio:m}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=v==null?void 0:v.endPTS)!==null&&h!==void 0?h:0)-((c=v==null?void 0:v.startPTS)!==null&&c!==void 0?c:0))*1e3),t.currentAudioSegmentLength$.next((((f=m==null?void 0:m.endPTS)!==null&&f!==void 0?f:0)-((p=m==null?void 0:m.startPTS)!==null&&p!==void 0?p:0))*1e3)}),this.subscription.add(Ue(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var h;return(h=Array.from(this.trackLevels.values()).find(({level:c})=>c===u))===null||h===void 0?void 0:h.track},l=Nt(this.hls,Ae.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ue(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var h;if(a.isNullable(u))return;const c=(h=this.trackLevels.get(u.id))===null||h===void 0?void 0:h.level;if(!c)return;const f=this.hls.levels.indexOf(c),p=this.hls.currentLevel,v=this.hls.levels[p];!v||c.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(B.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return G(this,void 0,void 0,function*(){this.videoState.startTransitionTo(B.PLAYING),(yield Et(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(B.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.removeAttribute("src"),this.video.load(),this.videoState.setState(B.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const wo="X-Playback-Duration";var Co=i=>G(void 0,void 0,void 0,function*(){var e;const t=yield di(i),r=yield t.text(),s=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(r))===null||e===void 0?void 0:e[1];return s?parseInt(s,10):t.headers.has(wo)?parseInt(t.headers.get(wo),10):void 0});const yy=i=>{let e=null;if(i.QUALITY&&(e=yr(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=a.videoSizeToQuality({width:t,height:r})}return e!=null?e:null},Ty=(i,e)=>{var t,r;const s=i.split(`
46
- `),n=[],o=[];for(let l=0;l<s.length;l++){const d=s[l],u=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!h)){if(u){const c=rr(u[1].split(",").map(y=>y.split("="))),f=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,p=yy(c);let v;c.BANDWIDTH&&(v=parseInt(c.BANDWIDTH,10)/1e3||void 0),!v&&c["AVERAGE-BANDWIDTH"]&&(v=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let b;if(c.RESOLUTION){const[y,T]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&T&&(b={width:y,height:T})}const S=new URL(s[++l],e).toString();p&&n.push({id:f,quality:p,url:S,bandwidth:v,size:b,fps:m})}if(h){const c=rr(h[1].split(",").map(m=>m.split("=")).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),f=(r=c.URI)===null||r===void 0?void 0:r.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,v=c.NAME;f&&p&&o.push({type:"internal",id:p,label:v,language:p,url:f,isAuto:!1})}}}if(!n.length)throw new Error("Empty manifest");return{qualityManifests:n,textTracks:o}},Ey=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let ys=0;const Na=(i,e=i,t)=>G(void 0,void 0,void 0,function*(){const s=yield(yield di(i)).text();ys+=1;try{const{qualityManifests:n,textTracks:o}=Ty(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(ys<=t.manifestRetryMaxCount)return yield Ey(a.getExponentialDelay(ys-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Na(i,e,t)}return{qualityManifests:[],textTracks:[]}});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class $y{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new Z(Y.STOPPED),this.textTracksManager=new tt,this.manifests$=new a.ValueSubject([]),this.liveOffset=new Ia,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.removeAttribute("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(Y.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d||u){const f=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===N.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(Y.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);else{let f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},Na(Ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:a.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Me(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,r,s;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(s=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(r=o.getState())===null||r===void 0?void 0:r.id)!==null&&s!==void 0?s:"master",h=this.manifests$.getValue();if(!h.length)return;const c=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),h.find(f=>f.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=Tt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(yt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,s.playbackRateState$,r)),n(Kt(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const c=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===c);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Me(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===N.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const h=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(h||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:h,bandwidth:c,fps:f})=>({id:d,quality:u,size:h,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){var e,t;const r=this.selectManifest();if(a.isNullable(r))return;const s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(r.url);if((s||n)&&r.id===this.masterManifest.id){const{max:u,min:h}=(t=(e=s==null?void 0:s.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[c,f]of[[u,"mq"],[h,"lq"]]){const p=String(parseFloat(c||""));f&&c&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?re.DASH_CMAF_OFFSET_P:re.OFFSET_P,d=Ce(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",d),this.video.load(),Co(d).then(u=>{var h;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const c=(h=this.params.source.maxSeekBackTime)!==null&&h!==void 0?h:this.maxSeekBackTime$.getValue();if(a.isNullable(c)||!isFinite(c))try{di(d).then(f=>f.text()).then(f=>{var p;const v=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(v){const m=new URL(v,d).toString();Co(m).then(b=>{a.isNullable(b)||this.maxSeekBackTime$.next(b)})}})}catch(f){}}})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(z||(z={}));class ky{constructor(e){this.subscription=new a.Subscription,this.videoState=new Z(z.STOPPED),this.textTracksManager=new tt,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(s===exports.PlaybackState.STOPPED){r!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(r===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l||d){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:f}=this.video;this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),h.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&h.state===N.Requested&&this.seek(h.position),r){case z.READY:s===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Na(Ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,r,s;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(s=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(r=o.getState())===null||r===void 0?void 0:r.id)!==null&&s!==void 0?s:"master",h=this.manifests$.getValue();if(!h.length)return;const c=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),h.find(f=>f.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=Tt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));if(n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ti(this.video,t.isLooped,r)),this.subscription.add(yt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{var l;const d=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),h=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(h&&a.isNonNullable(h.to)){const f=h.to.id;this.params.desiredState.videoTrack.setState(h.to);const p=this.manifests$.getValue().find(v=>v.id===f);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Me(p.url));const v=this.params.desiredState.playbackRate.getState(),m=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(v!==m){const b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(v),b.playbackRate=v)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===z.CHANGING_MANIFEST&&this.videoState.setState(u.to),d.state===N.Requested&&this.seek(d.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:h,bandwidth:c,fps:f})=>({id:d,quality:u,size:h,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},r))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){var e,t;const r=this.selectManifest();if(a.isNullable(r))return;const s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(r.url);if((s||n)&&r.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=s==null?void 0:s.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,h]of[[l,"mq"],[d,"lq"]]){const c=String(parseFloat(u||""));h&&u&&o.searchParams.set(h,c)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));class Py{constructor(e){this.subscription=new a.Subscription,this.videoState=new Z(X.STOPPED),this.trackUrls={},this.textTracksManager=new tt,this.syncPlayback=()=>{var t,r,s;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.video.removeAttribute("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(X.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),h=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(u&&n!==X.READY&&!h){this.handleQualityLimitTransition(u.to.max);return}if(n===X.STOPPED){this.videoState.startTransitionTo(X.READY),this.prepare();return}if(h){const{currentTime:f}=this.video;this.prepare(),c.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:f*1e3,forcePrecise:!0}),h.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((s=(r=this.trackUrls[h.to.id])===null||r===void 0?void 0:r.track)===null||s===void 0?void 0:s.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===N.Requested&&this.seek(c.position),n){case X.READY:o===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed());return;case X.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=St(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=Tt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ti(this.video,t.isLooped,r)),this.subscription.add(yt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,s.playbackRateState$,r)),n(Kt(this.video),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l,d;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===X.READY&&this.videoState.setState(X.READY);const u=this.params.desiredState.videoTrack.getTransition();if(u&&a.isNonNullable(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);const h=this.params.desiredState.playbackRate.getState(),c=(d=this.params.output.element$.getValue())===null||d===void 0?void 0:d.playbackRate;if(h!==c){const f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(h),f.playbackRate=h)}}this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),gt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[t];a.assertNonNullable(r,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(r=ia(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Me(r))}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,r,s,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(r=Object.values(this.trackUrls).find(c=>!a.isInvariantQuality(c.track.quality)&&a.isLowerOrEqual(c.track.quality,e)))===null||r===void 0?void 0:r.track,u=(s=this.params.desiredState.videoTrack.getState())===null||s===void 0?void 0:s.id,h=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(d&&h&&a.isHigherOrEqual(h.quality,d.quality)&&(o=d),!o){const c=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.isHigher(p.track.quality,e)),f=c.length;f&&(o=c[f-1].track)}o&&(l=o.quality)}else if(!e){const d=Object.values(this.trackUrls).map(u=>u.track);o=Tr(d,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.startTransitionTo(o)),this.params.output.autoVideoTrackLimits$.next({max:l})}}const Io=["stun:videostun.mycdn.me:80"],Ay=1e3,wy=3,Ts=()=>null;class Cy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ts,this.externalStopCallback=Ts,this.externalErrorCallback=Ts,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return G(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return G(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Io}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return G(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return G(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return G(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return G(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Ay)}normalizeOptions(e={}){const t={stunServerList:Io,maxRetryNumber:wy,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class Iy{constructor(e){this.videoState=new Z(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=St(e.container),this.liveStreamClient=new Cy(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.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),gt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=Tt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(Kt(this.video),this.params.output.elementVisible$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(yt(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a.VideoQuality.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class _o{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!!this.current.done}}var ce;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})(ce||(ce={}));var Je;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Je||(Je={}));var Es,$s,ks,Ps,Gi,As,Yi,ws,qi,Cs,Wi,Is,zi,_s,Qi,Rs;const Su=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Xe=document.createElement("video"),_y='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ry='video/mp4; codecs="hev1.1.6.L93.B0"',gu='video/webm; codecs="vp09.00.10.08"',yu='video/webm; codecs="av01.0.00M.08"',Ly='audio/mp4; codecs="mp4a.40.2"',Dy='audio/webm; codecs="opus"',ut={mms:vu(),mse:uy(),hls:!!(!((Es=Xe.canPlayType)===null||Es===void 0)&&Es.call(Xe,"application/x-mpegurl")||!(($s=Xe.canPlayType)===null||$s===void 0)&&$s.call(Xe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ye={mp4:!!(!((ks=Xe.canPlayType)===null||ks===void 0)&&ks.call(Xe,"video/mp4")),webm:!!(!((Ps=Xe.canPlayType)===null||Ps===void 0)&&Ps.call(Xe,"video/webm")),cmaf:!0},Oe={h264:!!(!((As=(Gi=lt())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||As===void 0)&&As.call(Gi,_y)),h265:!!(!((ws=(Yi=lt())===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||ws===void 0)&&ws.call(Yi,Ry)),vp9:!!(!((Cs=(qi=lt())===null||qi===void 0?void 0:qi.isTypeSupported)===null||Cs===void 0)&&Cs.call(qi,gu)),av1:!!(!((Is=(Wi=lt())===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||Is===void 0)&&Is.call(Wi,yu)),aac:!!(!((_s=(zi=lt())===null||zi===void 0?void 0:zi.isTypeSupported)===null||_s===void 0)&&_s.call(zi,Ly)),opus:!!(!((Rs=(Qi=lt())===null||Qi===void 0?void 0:Qi.isTypeSupported)===null||Rs===void 0)&&Rs.call(Qi,Dy))},si=(Oe.h264||Oe.h265)&&Oe.aac;let ct;const xy=()=>G(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:yu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:gu})}))]);ct={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{xy()}catch(i){console.error(i)}const hi=ut.hls&&ye.mp4,Ny=()=>Object.keys(Oe).filter(i=>Oe[i]),Oy=(i,e=!1,t=!1)=>{const r=ut.mse||ut.mms&&t;return i.filter(s=>{switch(s){case exports.VideoFormat.DASH_SEP:return r&&ye.mp4&&si;case exports.VideoFormat.DASH_WEBM:return r&&ye.webm&&Oe.vp9&&Oe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return r&&ye.webm&&Oe.av1&&Oe.opus;case exports.VideoFormat.DASH_LIVE:return ut.mse&&ye.mp4&&si;case exports.VideoFormat.DASH_LIVE_CMAF:return r&&ye.mp4&&si&&ye.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return r&&ye.mp4&&si;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return hi||e&&ut.mse&&ye.mp4&&si;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return hi;case exports.VideoFormat.MPEG:return ye.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ut.webrtc&&ut.ws&&Oe.h264&&(ye.mp4||ye.webm);default:return a.assertNever(s)}})},Ke=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case Je.VP9:return[e,t];case Je.AV1:return[t,e];case Je.NONE:return[];case Je.SMOOTH:return ct?ct[t].smooth?[t,e]:ct[e].smooth?[e,t]:[t,e]:[e,t];case Je.POWER_EFFICIENT:return ct?ct[t].powerEfficient?[t,e]:ct[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},My=({webmCodec:i,androidPreferredFormat:e})=>{if(Su)switch(e){case ce.MPEG:return[exports.VideoFormat.MPEG,...Ke(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ce.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ke(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case ce.DASH:return[...Ke(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];case ce.DASH_ANY_MPEG:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,...Ke(i),exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ce.DASH_ANY_WEBM:return[...Ke(i),exports.VideoFormat.MPEG,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ce.DASH_SEP:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.MPEG,...Ke(i),exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];default:a.assertNever(e)}return hi?[...Ke(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...Ke(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},By=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const r=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...r,...s],o=[...s,...r];let l;if(Su)switch(i){case ce.DASH:case ce.DASH_ANY_MPEG:case ce.DASH_ANY_WEBM:case ce.DASH_SEP:{l=n;break}case ce.HLS:case ce.MPEG:{l=o;break}default:a.assertNever(i)}else hi?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},Ro=i=>i?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Vy=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:h})=>`${u}-${h}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Fy={chunkDuration:5e3,maxParallelRequests:5};class Uy{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),currentVideoSegmentLength$:new a.ValueSubject(0),currentAudioSegmentLength$:new a.ValueSubject(0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),autoVideoTrackLimits$:new a.ValueSubject(void 0),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,warning$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),isLowLatency$:new a.ValueSubject(!1),canChangePlaybackSpeed$:new a.ValueSubject(!0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0),elementVisible$:new a.ValueSubject(!0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Oy([...By(this.params.tuning),...My(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:r,formatsToAvoid:s}=this.params.tuning;let n=[];r?n=[r]:s.length?n=[...t.filter(l=>!s.includes(l)),...t.filter(l=>s.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new _o(n);const o=[...Ro(!0),...Ro(!1)];this.chromecastFormatsIterator=new _o(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),s=r.state!==N.None;if(this.params.desiredState.seekState.setState({state:N.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return a.assertNonNullable(l),new by(Object.assign(Object.assign({},o),{source:l,sourceHls:d}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Sy(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),hi||!this.params.tuning.useHlsJs?new ky(Object.assign(Object.assign({},o),{source:l})):new gy(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new $y(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Py(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new kS(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},Fy),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Iy({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Fb({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case le.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return rr(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Vy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const n=this.current$.getValue().destination;if(n===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(le.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=s.category===a.ErrorCategory.NETWORK,l=s.category===a.ErrorCategory.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!l;d&&!l&&(o&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:le.SCREEN)}})),e}}const jy=5e3,Lo="one_video_throughput",Do="one_video_rtt",Ge=window.navigator.connection,xo=()=>{const i=Ge==null?void 0:Ge.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},No=()=>{const i=Ge==null?void 0:Ge.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},Oo=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class li{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=li.load(Lo)||(e.useBrowserEstimation?xo():void 0)||jy,n=(r=(t=li.load(Do))!==null&&t!==void 0?t:e.useBrowserEstimation?No():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Oo(s,n,e.rttPenaltyRequestSize)),this.throughput=ra.getSmoothedValue(s,-1,e),this.rtt=ra.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=xo();d&&this.throughput.next(d);const u=No();a.isNonNullable(u)&&this.rtt.next(u)};Ge&&"onchange"in Ge&&this.subscription.add(a.fromEvent(Ge,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Lo,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Do,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>Oo(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const r=e.getReader();if(!r){e.cancel("Could not get reader");return}let s=0,n=a.now(),o=0,l=a.now();const d=h=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},u=({done:h,value:c})=>G(this,void 0,void 0,function*(){if(h)!t&&this.addRawSpeed(s,a.now()-n,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(a.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=c.byteLength;else{const p=l-n;p&&this.addRawSpeed(o,p,1,t),o=c.byteLength,n=a.now()}l=a.now()}else s+=c.byteLength,o+=c.byteLength,o>=this.tuningConfig.streamMinSampleSize&&a.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,a.now()-l,this.concurrentDownloads.size),o=0,l=a.now());yield r==null?void 0:r.read().then(u,d)}});this.concurrentDownloads.add(e),r==null||r.read().then(u,d)}addRawSpeed(e,t,r=1,s=!1){if(li.sanityCheck(e,t,s)){const n=e*8/t;this.throughput.next(n*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var t;const r=a.safeStorage.get(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const Mo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:a.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:a.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Je.VP9,androidPreferredFormat:ce.MPEG,preferCMAF:!1,preferWebRTC:!1,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,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Hy=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,Mo)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Mo.configName]})};var Bo=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===N.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===N.None))),Gy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const Yy=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{s.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};class qy{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new a.ValueSubject(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new Z(exports.PlaybackState.STOPPED),seekState:new Z({state:N.None}),volume:new Z({volume:1,muted:!1}),videoTrack:new Z(void 0),autoVideoTrackSwitching:new Z(!0),autoVideoTrackLimits:new Z({}),isLooped:new Z(!1),playbackRate:new Z(1),externalTextTracks:new Z([]),internalTextTracks:new Z([]),currentTextTrack:new Z(void 0),textTrackCuesSettings:new Z({}),cameraOrientation:new Z({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1),currentVideoSegmentLength$:new a.ValueSubject(0),currentAudioSegmentLength$:new a.ValueSubject(0)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:nS},this.initLogs(),this.tuning=Hy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new zu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(c=>JSON.stringify(c,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,h=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:h,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=Gy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Uy({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zs()?a.fromEvent(document,"visibilitychange").pipe(a.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const r=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=r&&!s&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:N.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){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return Yy(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const r=this.getScene3D();if(r){const s=r.getCameraRotation(),n=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===N.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const r=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=r==null?void 0:r.provider)===null||t===void 0)&&t.scene3D)return r.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===N.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:N.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,d)=>a.isInvariantQuality(l)?1:a.isInvariantQuality(d)?-1:a.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(a.map(o=>o?{start:o.from,end:o.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.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(a.combine({hasLiveOffsetByPaused:a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(o=>o.to),a.filterChanged(),a.map(o=>o===exports.PlaybackState.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:o,isLowLatency:l})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),o){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(l));return}this.hasLiveOffsetByPaused.next(!1)})).add(a.combine({atLiveEdge:a.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(a.map(({isLive:o,position:l,isLowLatency:d})=>{const u=this.getActiveLiveDelay(d);return o&&Math.abs(l)<u/1e3}),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(a.map(({atLiveEdge:o,hasPausedTimeoutCase:l})=>o&&!l)).subscribe(this.info.atLiveEdge$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(a.map(({isLive:o,position:l,duration:d})=>o&&(Math.abs(d)-Math.abs(l))*1e3<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Bo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||r.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue();let c;h===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?u?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.INVISIBLE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var t;let r;const s=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;s&&(r=e.find(({quality:n})=>n===s),r||this.setAutoQuality(!0)),r||(r=Tr(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,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(r),this.info.currentQuality$.next(r.quality),this.info.videoBitrate$.next(r.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),aS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>sS(r)),this.providerContainer.current$.subscribe(({type:r})=>ji("provider",r)),t.duration$.subscribe(r=>ji("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>ji("tracks",r)),this.events.fatalError$.subscribe(new xe("fatalError")),this.events.managedError$.subscribe(new xe("managedError")),t.position$.subscribe(new xe("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new xe("quality")),this.info.currentBuffer$.subscribe(new xe("buffer")),t.isBuffering$.subscribe(new xe("isBuffering"))].forEach(r=>this.subscription.add(r)),ji("codecs",Ny())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>G(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const r=e.find(s=>s.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const Wy=`@vkontakte/videoplayer-core@${Vo}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return a.VideoQuality}});exports.Player=qy;exports.SDK_VERSION=Wy;exports.VERSION=Vo;
56
+
57
+ varying vec2 v_texel; // [0..1, 0..1]
58
+
59
+ uniform sampler2D u_texture;
60
+ uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
61
+
62
+ void main(void) {
63
+ // center point of output projection
64
+ float lambda0 = u_focus.x / 360.0;
65
+ float phi0 = u_focus.y / 180.0;
66
+
67
+ float lambda = PI * 2.0 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
68
+ float phi = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
69
+
70
+ float p = sqrt(lambda * lambda + phi * phi); // rou
71
+ float c = atan(p);
72
+ float cos_c = cos(c);
73
+ float sin_c = sin(c);
74
+
75
+ // geo coordinates of projection
76
+ float x = lambda0 + atan(
77
+ lambda * sin_c,
78
+ p * cos(phi0) * cos_c - phi * sin(phi0) * sin_c
79
+ );
80
+ float y = asin(cos_c * sin(phi0) + (phi * sin_c * cos(phi0)) / p);
81
+
82
+ // reprojected texture coordinates
83
+ vec2 tc = vec2(
84
+ mod(x / (PI * 2.0) - 0.5, 1.0), // [0..1]
85
+ mod(y / PI - 0.5, 1.0) // [0..1]
86
+ );
87
+
88
+ // sample using new coordinates
89
+ gl_FragColor = texture2D(u_texture, tc);
90
+ }
91
+ `;var fs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new ps(this.params.fov,this.params.orientation),this.cameraRotationManager=new hs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Sm,this.gl.VERTEX_SHADER),r=this.createShader(ym,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var rr=class{constructor(e){this.subscription=new C.Subscription;this.videoState=new G("stopped");this.elementSize$=new C.ValueSubject(void 0);this.textTracksManager=new Ve;this.droppedFramesManager=new rs;this.videoTracks$=new C.ValueSubject([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new es;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-l,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("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("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,C.assertNever)(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new fs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ds({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ke(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:C.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe((0,C.map)(l=>l.map(({track:c})=>c)))}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,C.filter)(C.isNonNullable),(0,C.once)()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(rt(this.video,t.isLooped,a)),this.subscription.add(we(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,C.observeElementSize)(this.video),this.elementSize$),s(_e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var c;if(l==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();(0,C.assertNonNullable)(p,"Manifest not loaded or empty");let f=Array.from(p.audio).sort((y,v)=>v.bitrate-y.bitrate),m=Array.from(p.video).sort((y,v)=>v.bitrate-y.bitrate),g=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let y of f){let v=um(y);v&&this.audioTracks.push({track:v,representation:y})}for(let y of m){let v=om(y);if(v){d.push({track:v,representation:y});let E=!this.params.tuning.isAudioDisabled&&lm(f,m,y);E&&this.audioRepresentations.set(y.id,E)}}this.videoTracks$.next(d);for(let y of g){let v=cm(y);v&&this.textTracks.push({track:v,representation:y})}this.params.output.availableVideoTracks$.next(d.map(({track:y})=>y)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:y})=>y)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:y})=>y));let S=this.selectVideoRepresentation();(0,C.assertNonNullable)(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))==null?void 0:c.id,this.params.sourceHls)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:C.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});this.subscription.add((0,C.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,C.fromEvent)(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(l!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let f=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let g=d.id;!this.params.output.elementVisible$.getValue()&&f&&(g=this.videoTracks$.getValue().map(y=>y.representation).sort((y,v)=>v.bitrate-y.bitrate).filter(y=>{let v=(0,C.videoSizeToQuality)(y),E=(0,C.videoSizeToQuality)(d);if(v&&E)return(0,C.isLowerOrEqual)(v,E)&&(0,C.isLowerOrEqual)(v,m)}).map(y=>y.id)[0]),this.player.switchRepresentation("video",g).catch(n);let S=this.audioRepresentations.get(d.id);S&&this.player.switchRepresentation("audio",S.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,C.filterChanged)(),(0,C.map)(l=>{var c;return l&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,C.map)(({to:l})=>l==="ready"),(0,C.filterChanged)());this.subscription.add((0,C.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,C.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,C.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,C.observableFrom)(["init"])).pipe((0,C.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,f,m,g,S,y;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:v}})=>v===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=Ct(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(r&&!e&&(m=(f=this.audioRepresentations.get(r.id))==null?void 0:f.bitrate)!=null?m:0,a&&(S=(g=this.audioRepresentations.get(a.id))==null?void 0:g.bitrate)!=null?S:0),l=$t(this.videoTracks$.getValue().map(({track:v})=>v),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?l!=null?l:r:r!=null?r:l;return c&&((y=this.videoTracks$.getValue().find(({track:v})=>v===c))==null?void 0:y.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}};var Ui=class extends rr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ir=require("@vkontakte/videoplayer-shared");var Hi=class extends rr{constructor(e){super(e),this.liveOffset=new dt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,ir.combine)({interval:(0,ir.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,ir.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ir.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var Tm=He(Ja(),1);var H=require("@vkontakte/videoplayer-shared");var Ke={};var Dr=(i,e)=>new H.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),ji=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new G("initializing");this.textTracksManager=new Ve;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.video=xe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Tm.default)(import("hls.js").then(a=>{e||(Ke.Hls=a.default,Ke.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,H.assertNonNullable)(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ke(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,r)),this.subscription.add(we(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Be(this.video,e.playbackRate,a.playbackRateState$,r)),s(_e(this.video),t.elementVisible$),this.subscription.add(Dr(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Dr(this.hls,Ke.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:l})=>l.reduce((c,d)=>{var v,E;let p=d.name||d.height.toString(10),{width:f,height:m}=d,g=(E=Lt((v=d.attrs.QUALITY)!=null?v:""))!=null?E:(0,H.videoSizeToQuality)({width:f,height:m});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:f,height:m},fps:S};return this.trackLevels.set(p,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),s(Dr(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,f=d.attrs.URI||"",m=d.lang,g="internal";c.push({id:p,url:f,language:m,type:g})}e.internalTextTracks.startTransitionTo(c)}}),s(Dr(this.hls,Ke.Events.LEVEL_LOADING).pipe((0,H.map)(({url:l})=>fe(l))),t.hostname$),s(Dr(this.hls,Ke.Events.FRAG_CHANGED),l=>{var p,f,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Rt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Dr(this.hls,Ke.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Rt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,H.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,f=this.hls.levels[p];!f||c.bitrate>f.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return _(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("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.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Im="X-Playback-Duration",Qo=i=>_(void 0,null,function*(){var a;let e=yield ft(i),t=yield e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(Im)?parseInt(e.headers.get(Im),10):void 0});var F=require("@vkontakte/videoplayer-shared");var Ko=He(Na(),1);var ms=require("@vkontakte/videoplayer-shared");var hP=i=>{let e=null;if(i.QUALITY&&(e=Lt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,ms.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},fP=(i,e)=>{var s,n;let t=i.split(`
92
+ `),r=[],a=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Ko.default)(l[1].split(",").map(v=>v.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,f=hP(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[v,E]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));v&&E&&(S={width:v,height:E})}let y=new URL(t[++o],e).toString();f&&r.push({id:p,quality:f,url:y,bandwidth:m,size:S,fps:g})}if(c){let d=(0,Ko.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),f=d.LANGUAGE,m=d.NAME;p&&f&&a.push({type:"internal",id:f,label:m,language:f,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},mP=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),zo=0,Em=(r,...a)=>_(void 0,[r,...a],function*(i,e=i,t){let n=yield(yield ft(i)).text();zo+=1;try{let{qualityManifests:o,textTracks:u}=fP(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(zo<=t.manifestRetryMaxCount)return yield mP((0,ms.getExponentialDelay)(zo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Em(i,e,t)}return{qualityManifests:[],textTracks:[]}}),bs=Em;var Gi=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new G("stopped");this.textTracksManager=new Ve;this.manifests$=new F.ValueSubject([]);this.liveOffset=new dt;this.manifestStartTime$=new F.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("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("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(a==null?void 0:a.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("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);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(a==null?void 0:a.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,F.assertNever)(t)}};var t;this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F.VideoQuality.INVARIANT,url:this.params.source.url},bs(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:F.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:F.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.maxSeekBackTime$=new F.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:F.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ke(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(we(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,a.playbackRateState$,r)),s(_e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,F.filterChanged)(),(0,F.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,F.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(fe(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,F.combine)({startTime:this.manifestStartTime$.pipe((0,F.filter)(F.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,F.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,F.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,F.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let f=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ge(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Qo(n).then(l=>{var c;if(!(0,F.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,F.isNullable)(d)||!isFinite(d))try{ft(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();Qo(g).then(S=>{(0,F.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){Ae(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var W=require("@vkontakte/videoplayer-shared");var Yi=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new G("stopped");this.textTracksManager=new Ve;this.manifests$=new W.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("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("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(a==null?void 0:a.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,W.assertNever)(t)}};this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:W.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),bs(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:W.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:W.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ke(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(we(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,W.isNonNullable)(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===p);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(fe(f.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,W.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!(0,W.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,W.merge)((0,W.fromEvent)(o,"addtrack"),(0,W.fromEvent)(o,"removetrack"),(0,W.fromEvent)(o,"change"),(0,W.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,W.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,W.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Ae(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ee=require("@vkontakte/videoplayer-shared");var Wi=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new Ve;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("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("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,ee.assertNever)(e)}};this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:ee.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ke(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(we(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,a.playbackRateState$,r)),s(_e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ee.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Pe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,ee.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ee.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(fe(t))}playIfAllowed(){Ae(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,ee.isInvariantQuality)(d.track.quality)&&(0,ee.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,ee.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(f=>!(0,ee.isInvariantQuality)(f.track.quality)&&(0,ee.isHigher)(f.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=$t(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var ae=require("@vkontakte/videoplayer-shared");var Pm=require("@vkontakte/videoplayer-shared");var xm=["stun:videostun.mycdn.me:80"],bP=1e3,gP=3,Jo=()=>null,gs=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Jo;this.externalStopCallback=Jo;this.externalErrorCallback=Jo;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return _(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return _(this,null,function*(){try{let e={iceServers:[{urls:xm}]};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);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return _(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return _(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Pm.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return _(this,null,function*(){let 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){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return _(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let 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),bP)}normalizeOptions(e={}){let t={stunServerList:xm,maxRetryNumber:gP,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Qi=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new ae.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("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("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}};this.subscription=new ae.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=xe(e.container),this.liveStreamClient=new gs(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.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ae.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ae.merge)(this.videoState.stateChangeStarted$.pipe((0,ae.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ae.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ke(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(_e(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(we(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ae.assertNever)(n.to)}},r)).add((0,ae.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ae.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("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:ae.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var zi=class{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!!this.current.done}};var I=require("@vkontakte/videoplayer-shared");var vt=require("@vkontakte/videoplayer-shared");var Bm=(0,vt.getCurrentBrowser)().device===vt.CurrentClientDevice.Android,qe=document.createElement("video"),yP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',TP='video/mp4; codecs="hev1.1.6.L93.B0"',Vm='video/webm; codecs="vp09.00.10.08"',_m='video/webm; codecs="av01.0.00M.08"',IP='audio/mp4; codecs="mp4a.40.2"',EP='audio/webm; codecs="opus"',wm,km,ar={mms:cs(),mse:mm(),hls:!!((wm=qe.canPlayType)!=null&&wm.call(qe,"application/x-mpegurl")||(km=qe.canPlayType)!=null&&km.call(qe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Am,Rm,Fe={mp4:!!((Am=qe.canPlayType)!=null&&Am.call(qe,"video/mp4")),webm:!!((Rm=qe.canPlayType)!=null&&Rm.call(qe,"video/webm")),cmaf:!0},vs,Lm,Ss,$m,ys,Cm,Ts,Dm,Is,Mm,Es,Om,at={h264:!!((Lm=(vs=gt())==null?void 0:vs.isTypeSupported)!=null&&Lm.call(vs,yP)),h265:!!(($m=(Ss=gt())==null?void 0:Ss.isTypeSupported)!=null&&$m.call(Ss,TP)),vp9:!!((Cm=(ys=gt())==null?void 0:ys.isTypeSupported)!=null&&Cm.call(ys,Vm)),av1:!!((Dm=(Ts=gt())==null?void 0:Ts.isTypeSupported)!=null&&Dm.call(Ts,_m)),aac:!!((Mm=(Is=gt())==null?void 0:Is.isTypeSupported)!=null&&Mm.call(Is,IP)),opus:!!((Om=(Es=gt())==null?void 0:Es.isTypeSupported)!=null&&Om.call(Es,EP))},Ki=(at.h264||at.h265)&&at.aac,sr,xP=()=>_(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(z(M({},i),{video:z(M({},i.video),{contentType:_m})})),window.navigator.mediaCapabilities.decodingInfo(z(M({},i),{video:z(M({},i.video),{contentType:Vm})}))]);sr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{xP()}catch(i){console.error(i)}var Mr=ar.hls&&Fe.mp4,Nm=()=>Object.keys(at).filter(i=>at[i]),Fm=(i,e=!1,t=!1)=>{let r=ar.mse||ar.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Fe.mp4&&Ki;case"DASH_WEBM":return r&&Fe.webm&&at.vp9&&at.opus;case"DASH_WEBM_AV1":return r&&Fe.webm&&at.av1&&at.opus;case"DASH_LIVE":return ar.mse&&Fe.mp4&&Ki;case"DASH_LIVE_CMAF":return r&&Fe.mp4&&Ki&&Fe.cmaf;case"DASH_ONDEMAND":return r&&Fe.mp4&&Ki;case"HLS":case"HLS_ONDEMAND":return Mr||e&&ar.mse&&Fe.mp4&&Ki;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Mr;case"MPEG":return Fe.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ar.webrtc&&ar.ws&&at.h264&&(Fe.mp4||Fe.webm);default:return(0,vt.assertNever)(a)}})},Mt=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return sr?sr[t].smooth?[t,e]:sr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return sr?sr[t].powerEfficient?[t,e]:sr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,vt.assertNever)(i)}return[e,t]},qm=({webmCodec:i,androidPreferredFormat:e})=>{if(Bm)switch(e){case"mpeg":return["MPEG",...Mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...Mt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...Mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...Mt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Mt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Mt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,vt.assertNever)(e)}return Mr?[...Mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...Mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Um=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(Bm)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,vt.assertNever)(i)}else Mr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Xo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var St=require("@vkontakte/videoplayer-shared"),Hm=i=>new St.Observable(e=>{let t=new St.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,St.map)(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,St.map)(({type:l})=>l!==void 0)),n=new St.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var PP={chunkDuration:5e3,maxParallelRequests:5},Ji=class{constructor(e){this.current$=new I.ValueSubject({type:void 0});this.providerError$=new I.Subject;this.noAvailableProvidersError$=new I.Subject;this.providerOutput={position$:new I.ValueSubject(0),duration$:new I.ValueSubject(1/0),volume$:new I.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new I.ValueSubject(void 0),currentVideoSegmentLength$:new I.ValueSubject(0),currentAudioSegmentLength$:new I.ValueSubject(0),availableVideoTracks$:new I.ValueSubject([]),availableAudioTracks$:new I.ValueSubject([]),isAudioAvailable$:new I.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new I.ValueSubject(!1),autoVideoTrackLimits$:new I.ValueSubject(void 0),currentBuffer$:new I.ValueSubject(void 0),isBuffering$:new I.ValueSubject(!0),error$:new I.Subject,warning$:new I.Subject,willSeekEvent$:new I.Subject,seekedEvent$:new I.Subject,loopedEvent$:new I.Subject,endedEvent$:new I.Subject,firstBytesEvent$:new I.Subject,firstFrameEvent$:new I.Subject,canplay$:new I.Subject,isLive$:new I.ValueSubject(void 0),isLowLatency$:new I.ValueSubject(!1),canChangePlaybackSpeed$:new I.ValueSubject(!0),liveTime$:new I.ValueSubject(void 0),liveBufferTime$:new I.ValueSubject(void 0),availableTextTracks$:new I.ValueSubject([]),currentTextTrack$:new I.ValueSubject(void 0),hostname$:new I.ValueSubject(void 0),httpConnectionType$:new I.ValueSubject(void 0),httpConnectionReused$:new I.ValueSubject(void 0),inPiP$:new I.ValueSubject(!1),inFullscreen$:new I.ValueSubject(!1),element$:new I.ValueSubject(void 0),elementVisible$:new I.ValueSubject(!0),availableSources$:new I.ValueSubject(void 0),is3DVideo$:new I.ValueSubject(!1)};this.subscription=new I.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Fm([...Um(this.params.tuning),...qm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,I.isNonNullable)(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new zi(s);let n=[...Xo(!0),...Xo(!1)];this.chromecastFormatsIterator=new zi(n.filter(o=>(0,I.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}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(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,I.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:I.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,I.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,I.assertNonNullable)(o),new Ui(z(M({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Hi(z(M({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),Mr||!this.params.tuning.useHlsJs?new Yi(z(M({},n),{source:o})):new ji(z(M({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Gi(z(M({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Wi(z(M({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new vf(z(M({},n),{source:o,config:z(M({},PP),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Qi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,I.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,I.assertNonNullable)(o),new ni({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,I.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,I.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,I.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return z(M({},e),{url:r(e.url)})}return(0,jm.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new I.Subscription,t=!1,r=0;return e.add((0,I.merge)(this.providerOutput.error$,Hm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,I.map)(a=>({id:`ProviderHangup:${a}`,category:I.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,I.filter)(({to:s})=>s==="playing"),(0,I.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===I.ErrorCategory.NETWORK,o=a.category===I.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};var O=require("@vkontakte/videoplayer-shared");var wP=5e3,Gm="one_video_throughput",Ym="one_video_rtt",yt=window.navigator.connection,Wm=()=>{let i=yt==null?void 0:yt.downlink;if((0,O.isNonNullable)(i)&&i!==10)return i*1e3},Qm=()=>{let i=yt==null?void 0:yt.rtt;if((0,O.isNonNullable)(i)&&i!==3e3)return i},zm=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Zo=class i{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(Gm)||(e.useBrowserEstimation?Wm():void 0)||wP,r=(s=(a=i.load(Ym))!=null?a:e.useBrowserEstimation?Qm():void 0)!=null?s:0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(r),this.rttAdjustedThroughput$=new O.ValueSubject(zm(t,r,e.rttPenaltyRequestSize)),this.throughput=er.getSmoothedValue(t,-1,e),this.rtt=er.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=Wm();u&&this.throughput.next(u);let l=Qm();(0,O.isNonNullable)(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add((0,O.fromEvent)(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{O.safeStorage.set(Gm,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{O.safeStorage.set(Ym,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:n,rtt:o})=>zm(n,o,e.rttPenaltyRequestSize)),(0,O.filter)(n=>{let 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,r=(0,O.now)(),a=new O.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,r=(0,O.now)()}));break;case 1:case 0:a.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,O.now)()}));break}a.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=(0,O.now)(),n=0,o=(0,O.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>_(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(a,(0,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if((0,O.now)()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,O.now)()}o=(0,O.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},Km=Zo;var Xi=require("@vkontakte/videoplayer-shared");var Jm={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Xi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Xi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,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,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Xm=i=>{var e;return z(M({},(0,Xi.fillWithDefault)(i,Jm)),{configName:[...(e=i.configName)!=null?e:[],...Jm.configName]})};var h=require("@vkontakte/videoplayer-shared");var Tt=require("@vkontakte/videoplayer-shared"),eu=({seekState:i,position$:e})=>(0,Tt.merge)(i.stateChangeEnded$.pipe((0,Tt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Tt.filter)(Tt.isNonNullable)),e.pipe((0,Tt.filter)(()=>i.getState().state==="none")));var Zm=require("@vkontakte/videoplayer-shared"),eb=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,Zm.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var xs=require("@vkontakte/videoplayer-shared"),tb=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,xs.filter)(a=>a.length>0),(0,xs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Zi=class{constructor(e={configName:[]}){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,firstBytes$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:ff};if(this.initLogs(),this.tuning=Xm(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ca({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Km(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(p,f)=>{let m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:h.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=eb(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Ji({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!pi()?(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,h.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>M({type:"external"},t))),this}selectTextTrack(e){var t;return tb(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(z(M({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(u)?-1:(0,h.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,h.map)(n=>n?{start:n.from,end:n.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.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:eu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(eu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,h.once)(),(0,h.map)(n=>n!=null?n:(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,h.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,h.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,h.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,h.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=$t(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,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),hf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>pf(r)),this.providerContainer.current$.subscribe(({type:r})=>ui("provider",r)),e.duration$.subscribe(r=>ui("duration",r)),e.availableVideoTracks$.pipe((0,h.filter)(r=>!!r.length),(0,h.once)()).subscribe(r=>ui("tracks",r)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe((0,h.map)(r=>r==null?void 0:r.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(r=>this.subscription.add(r)),ui("codecs",Nm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>_(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:h.ErrorCategory.DOM,message:String(a)})})});this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var st=require("@vkontakte/videoplayer-shared"),kP=`@vkontakte/videoplayer-core@${Os}`;