@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/esnext.esm.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
- import{ValueSubject as g,Subject as x,Subscription as ee,isNonNullable as A,ErrorCategory as P,isNullable as Q,fromEvent as C,assertNever as V,merge as O,tap as Ft,map as T,observableFrom as Ce,filterChanged as de,assertNonNullable as v,debounce as Ge,getHighestQuality as xs,timeout as Cs,getCurrentBrowser as Pi,CurrentClientBrowser as os,combine as De,once as Se,mapTo as Zt,filter as oe,VideoQuality as $e,now as ae,assertNotEmptyArray as Rs,videoSizeToQuality as dt,isInvariantQuality as ut,isHigher as kt,isLower as Jt,isHigherOrEqual as yi,isLowerOrEqual as ei,interval as Mt,Observable as Li,videoQualityToHeight as Is,abortable as Te,getExponentialDelay as Xt,throttle as Bs,observeElementSize as Ms,isIOS as _s,CurrentClientDevice as Os,safeStorage as mi,fillWithDefault as Ns,Logger as Fs}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as fn,Subject as pn,Subscription as mn,ValueSubject as gn,VideoQuality as Sn}from"@vkontakte/videoplayer-shared/esnext.esm.js";const Vs="2.0.103";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var m;(function(a){a.MPEG="MPEG",a.DASH="DASH_SEP",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(m||(m={}));var ge;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ge||(ge={}));var pe;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(pe||(pe={}));var Ti;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Ti||(Ti={}));var G;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(G||(G={}));var We;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible"})(We||(We={}));var Us=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Hs{connection$=new g(void 0);castState$=new g(pe.NOT_AVAILABLE);errorEvent$=new x;contentId;realCastState$=new g(pe.NOT_AVAILABLE);subscription=new ee;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const i=A(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},s||Us("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:P.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){A(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Q(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Q(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(C(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.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 V(s.sessionState)}})).add(O(C(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ft(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),T(s=>s.castState)),Ce([i.getCastState()])).pipe(de(),T(Ys),Ft(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const r=s===pe.CONNECTED,n=A(this.connection$.getValue());if(r&&!n){const o=i.getCurrentSession();v(o);const d=o.getCastDevice(),c=o.getMediaSession()?.media.contentId;(Q(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:d}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===pe.CONNECTED?A(this.connection$.getValue())?pe.CONNECTED:pe.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:P.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Ys=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return pe.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return pe.AVAILABLE;case cast.framework.CastState.CONNECTING:return pe.CONNECTING;case cast.framework.CastState.CONNECTED:return pe.CONNECTED;default:return V(a)}};var le;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(le||(le={}));var Oe=(a,e=0,t=le.OFFSET_P)=>{switch(t){case le.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case le.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case le.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:V(t)}return a};const _i=(a,e)=>{switch(e){case le.OFFSET_P:return NaN;case le.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case le.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:V(e)}};var R=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class ne{state;prevState;transition;transitionStarted$=new x;transitionEnded$=new x;transitionUpdated$=new x;forceChanged$=new x;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||A(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Gs=a=>{switch(a){case m.MPEG:case m.DASH_SEP:case m.DASH_ONDEMAND:case m.DASH_WEBM:case m.DASH_WEBM_AV1:case m.HLS:case m.HLS_ONDEMAND:return!1;case m.DASH_LIVE:case m.DASH_LIVE_CMAF:case m.HLS_LIVE:case m.HLS_LIVE_CMAF:case m.DASH_LIVE_WEBM:case m.WEB_RTC_LIVE:return!0;default:return V(a)}};var F;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(F||(F={}));const qs=5,zs=5,Ws=500,Oi=7e3;class Qs{subscription=new ee;loadMediaTimeoutSubscription=new ee;videoState=new ne(F.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Gs(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 ee;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(T(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(T(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,r)=>this.subscription.add(s.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new x;e.add(s.pipe(Ge(Ws)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===G.Applying||Math.abs(o-r)>qs)&&s.next(o),r=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:r}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),d=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&r.duration-r.currentTime<zs&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,l.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:V(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(F.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(F.PLAYING),R(this.params.desiredState.playbackState,l.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:G.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),R(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&R(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,r;switch(e){case m.MPEG:{const c=t[e];v(c);const u=xs(Object.keys(c));v(u);const h=c[u];v(h),i=h,s="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case m.HLS:case m.HLS_ONDEMAND:{const c=t[e];v(c),i=c.url,s="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case m.DASH_SEP:case m.DASH_ONDEMAND:case m.DASH_WEBM:case m.DASH_WEBM_AV1:{const c=t[e];v(c),i=c.url,s="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case m.DASH_LIVE_CMAF:{const c=t[e];v(c),i=c.url,s="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case m.HLS_LIVE:case m.HLS_LIVE_CMAF:{const c=t[e];v(c),i=Oe(c.url),s="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case m.DASH_LIVE:case m.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",u=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:P.VIDEO_PIPELINE,message:c,thrown:u}),u}case m.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:d}=this.params.meta;return A(o)&&(n.metadata.title=o),A(d)&&(n.metadata.subtitle=d),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===G.Applying||i.state===G.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,r)=>{this.loadMediaTimeoutSubscription.add(Cs(Oi).subscribe(()=>r(`timeout(${Oi})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===G.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:P.VIDEO_PIPELINE,message:r,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!t){if(s?.to!==l.PAUSED&&r.state===G.Requested&&e!==F.STOPPED){this.seek(r.position/1e3);return}switch(i){case l.READY:{switch(e){case F.PLAYING:case F.PAUSED:case F.READY:break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:V(e)}break}case l.PLAYING:{switch(e){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:V(e)}break}case l.PAUSED:{switch(e){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:V(e)}break}default:V(i)}}}}const Di=a=>{a.removeAttribute("src"),a.load()},js=a=>{try{a.pause(),a.playbackRate=0,Di(a),a.remove()}catch(e){console.error(e)}};class Js{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 vi=window.WeakMap?new WeakMap:new Js,lt=a=>{let e=a.querySelector("video");const t=!!e;return e?Di(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ft=a=>{const e=vi.get(a);vi.delete(a),e?Di(a):js(a)},Qe=(a,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:r}={})=>{const n=a.getState(),o=e(),d=Q(s),c=new ee;return s&&c.add(s.subscribe(u=>{const h=a.getState();i(u,h)&&a.setState(u)},r)),i(o,n)||(t(n),d&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(u=>{t(u.to),d&&a.setState(u.to)},r)),c},Ht=(a,e,t)=>Qe(e,()=>a.loop,i=>{A(i)&&(a.loop=i)},{onError:t}),pt=(a,e,t,i)=>Qe(e,()=>({muted:a.muted,volume:a.volume}),s=>{A(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,r)=>s===r||s?.muted===r?.muted&&s?.volume===r?.volume,changed$:t,onError:i}),Lt=(a,e,t,i)=>Qe(e,()=>a.playbackRate,s=>{A(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),Xs=a=>["__",a.language,a.label].join("|"),Ks=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class it{available$=new x;current$=new g(void 0);error$=new x;video;cueSettings;subscription=new ee;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=r=>{this.error$.next({id:"TextTracksManager",category:P.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Qe(t.internalTextTracks,()=>Object.values(this.internalTracks),r=>{A(r)&&this.setInternal(r)},{equal:(r,n)=>A(r)&&A(n)&&r.length===n.length&&r.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(T(r=>r.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(Qe(t.externalTextTracks,()=>Object.values(this.externalTracks),r=>{A(r)&&this.setExternal(r)},{equal:(r,n)=>A(r)&&A(n)&&r.length===n.length&&r.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(T(r=>r.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(Qe(t.currentTextTrack,()=>{if(this.video)return;const r=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return r&&this.htmlTextTrackToITextTrack(r).id},r=>this.select(r),{changed$:this.current$,onError:s})),this.subscription.add(Qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){v(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(O(C(e,"addtrack"),C(e,"removetrack"),Ce(["init"])).pipe(T(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),de((i,s)=>i.length===s.length&&i.every(({id:r},n)=>r===s[n].id))).subscribe(this.available$)),this.subscription.add(O(C(e,"change"),Ce(["init"])).pipe(T(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),T(i=>i&&this.htmlTextTrackToITextTrack(i).id),de()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(C(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(C(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;A(t.align)&&(s.align=t.align),A(t.position)&&(s.position=t.position),A(t.size)&&(s.size=t.size),A(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){v(this.video);const t=[...this.video.textTracks];return e?t:t.filter(it.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Xs(e),r=this.externalTracks.has(s),n=s.includes("auto");return r?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(s)?.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:r})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===r)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){v(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!Ks(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){v(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){v(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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 xi{pausedTime=0;streamOffset=0;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 cs=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ni=a=>{const e=cs(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Zs=a=>{const e=cs(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},ea=3;var ta=(a,e,t=ea)=>{let i=0,s=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let d=r-1;d>=0;d--)a.end(d)+t>=i&&(i=a.start(d));for(let d=r+1;d<a.length;d++)a.start(d)-t<=s&&(s=a.end(d))}}return{from:i,to:s}};const mt=a=>{const e=M=>C(a,M).pipe(Zt(void 0)),i=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>C(a,M))).pipe(T(M=>M.type==="ended"?a.readyState<2:a.readyState<3),de()),s=O(C(a,"progress"),C(a,"timeupdate")).pipe(T(()=>ta(a.buffered,a.currentTime))),n=Pi().browser===os.Safari?De({play:e("play").pipe(Se()),playing:e("playing")}).pipe(Zt(void 0)):e("playing"),o=C(a,"volumechange").pipe(T(()=>({muted:a.muted,volume:a.volume}))),d=C(a,"ratechange").pipe(T(()=>a.playbackRate)),c=C(a,"error").pipe(oe(()=>!!(a.error||a.played.length)),T(()=>{const M=a.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:P.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:a.error??void 0}})),u=C(a,"timeupdate").pipe(T(()=>a.currentTime)),h=new x,p=.3;let f;u.subscribe(M=>{a.loop&&A(f)&&A(M)&&f>=a.duration-p&&M<=p&&h.next(f),f=M});const S=C(a,"enterpictureinpicture"),w=C(a,"leavepictureinpicture"),y=new g(Zs(a));S.subscribe(()=>y.next(!0)),w.subscribe(()=>y.next(!1));const k=new g(Ni(a));return C(a,"fullscreenchange").pipe(T(()=>Ni(a))).subscribe(k),{playing$:n,pause$:e("pause").pipe(oe(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:C(a,"durationchange").pipe(T(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:d,inPiP$:y,inFullscreen$:k}};var ni=a=>{switch(a){case"mobile":return $e.Q_144P;case"lowest":return $e.Q_240P;case"low":return $e.Q_360P;case"sd":case"medium":return $e.Q_480P;case"hd":case"high":return $e.Q_720P;case"fullhd":case"full":return $e.Q_1080P;case"quadhd":case"quad":return $e.Q_1440P;case"ultrahd":case"ultra":return $e.Q_2160P}};let Ci=!1,je={};const ia=a=>{Ci=a},sa=()=>{je={}},aa=a=>{a(je)},Qt=(a,e)=>{Ci&&(je.meta=je.meta??{},je.meta[a]=e)};class Ue{name;constructor(e){this.name=e}next(e){if(!Ci)return;je.series=je.series??{};const t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}}var ot;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(ot||(ot={}));const ra=new Ue("best_bitrate"),na=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class oa{last;history={};recordSelection(e){this.history[e.id]=ae()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ca='Assertion "ABR Tracks is empty array" failed',oi=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:d,history:c,droppedVideoMaxQualityLimit:u,abrLogger:h})=>{Rs(a,ca);const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},S=f&&dt(f),w=i.considerPlaybackRate&&A(o)?o:1,y=a.filter(D=>!ut(D.quality)).sort((D,I)=>kt(D.quality,I.quality)?-1:1),k=y.at(-1)?.quality,_=y.at(0)?.quality,M=Q(s)||A(s.min)&&A(s.max)&&Jt(s.max,s.min)||A(s.min)&&_&&kt(s.min,_)||A(s.max)&&k&&Jt(s.max,k),E=w*na(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},q=y.filter(D=>(S?Jt(D.quality,S):!0)?(A(t)&&isFinite(t)&&A(D.bitrate)?t-r>=D.bitrate*E:!0)?i.lazyQualitySwitch&&A(i.minBufferToSwitchUp)&&d&&!ut(d.quality)&&(n??0)<i.minBufferToSwitchUp&&kt(D.quality,d.quality)?(L[D.quality]=ot.Buffer,!1):!!u&&yi(D.quality,u)?(L[D.quality]=ot.DroppedFramesLimit,!1):M||(Q(s.max)||ei(D.quality,s.max))&&(Q(s.min)||yi(D.quality,s.min))?!0:(L[D.quality]=ot.FitsQualityLimits,!1):(L[D.quality]=ot.FitsThroughput,!1):(L[D.quality]=ot.FitsContainer,!1))[0];q&&q.bitrate&&ra.next(q.bitrate);const U=q??y[Math.ceil((y.length-1)/2)]??a[0];U.quality!==c?.last?.quality&&h({message:`
6
+ var tg=Object.create;var gu=Object.defineProperty;var rg=Object.getOwnPropertyDescriptor;var ig=Object.getOwnPropertyNames;var ag=Object.getPrototypeOf,sg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ng=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ig(e))!sg.call(i,a)&&a!==t&&gu(i,a,{get:()=>e[a],enumerable:!(r=rg(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?tg(ag(i)):{},ng(e||!i||!i.__esModule?gu(t,"default",{value:i,enumerable:!0}):t,i));var ce=f((sR,Pu)=>{"use strict";Pu.exports=function(i){try{return!!i()}catch{return!0}}});var yr=f((nR,ku)=>{"use strict";var fg=ce();ku.exports=!fg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var X=f((oR,Ru)=>{"use strict";var wu=yr(),Au=Function.prototype,ws=Au.call,mg=wu&&Au.bind.bind(ws,ws);Ru.exports=wu?mg:function(i){return function(){return ws.apply(i,arguments)}}});var Ut=f((uR,$u)=>{"use strict";var Lu=X(),bg=Lu({}.toString),gg=Lu("".slice);$u.exports=function(i){return gg(bg(i),8,-1)}});var Du=f((lR,Cu)=>{"use strict";var vg=X(),Sg=ce(),yg=Ut(),As=Object,Tg=vg("".split);Cu.exports=Sg(function(){return!As("z").propertyIsEnumerable(0)})?function(i){return yg(i)=="String"?Tg(i,""):As(i)}:As});var Ht=f((cR,Mu)=>{"use strict";Mu.exports=function(i){return i==null}});var Wi=f((dR,Ou)=>{"use strict";var Ig=Ht(),Eg=TypeError;Ou.exports=function(i){if(Ig(i))throw Eg("Can't call method on "+i);return i}});var jt=f((pR,Bu)=>{"use strict";var xg=Du(),Pg=Wi();Bu.exports=function(i){return xg(Pg(i))}});var Rs=f((hR,Vu)=>{"use strict";Vu.exports=function(){}});var vt=f((fR,_u)=>{"use strict";_u.exports={}});var G=f((Nu,Fu)=>{"use strict";var Qi=function(i){return i&&i.Math==Math&&i};Fu.exports=Qi(typeof globalThis=="object"&&globalThis)||Qi(typeof window=="object"&&window)||Qi(typeof self=="object"&&self)||Qi(typeof global=="object"&&global)||function(){return this}()||Nu||Function("return this")()});var $s=f((mR,qu)=>{"use strict";var Ls=typeof document=="object"&&document.all,kg=typeof Ls>"u"&&Ls!==void 0;qu.exports={all:Ls,IS_HTMLDDA:kg}});var F=f((bR,Hu)=>{"use strict";var Uu=$s(),wg=Uu.all;Hu.exports=Uu.IS_HTMLDDA?function(i){return typeof i=="function"||i===wg}:function(i){return typeof i=="function"}});var Yu=f((gR,Gu)=>{"use strict";var Ag=G(),Rg=F(),ju=Ag.WeakMap;Gu.exports=Rg(ju)&&/native code/.test(String(ju))});var Be=f((vR,zu)=>{"use strict";var Wu=F(),Qu=$s(),Lg=Qu.all;zu.exports=Qu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Wu(i)||i===Lg}:function(i){return typeof i=="object"?i!==null:Wu(i)}});var Ve=f((SR,Ku)=>{"use strict";var $g=ce();Ku.exports=!$g(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var zi=f((yR,Xu)=>{"use strict";var Cg=G(),Ju=Be(),Cs=Cg.document,Dg=Ju(Cs)&&Ju(Cs.createElement);Xu.exports=function(i){return Dg?Cs.createElement(i):{}}});var Ds=f((TR,Zu)=>{"use strict";var Mg=Ve(),Og=ce(),Bg=zi();Zu.exports=!Mg&&!Og(function(){return Object.defineProperty(Bg("div"),"a",{get:function(){return 7}}).a!=7})});var Ms=f((IR,el)=>{"use strict";var Vg=Ve(),_g=ce();el.exports=Vg&&_g(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Pe=f((ER,tl)=>{"use strict";var Ng=Be(),Fg=String,qg=TypeError;tl.exports=function(i){if(Ng(i))return i;throw qg(Fg(i)+" is not an object")}});var Z=f((xR,rl)=>{"use strict";var Ug=yr(),Ki=Function.prototype.call;rl.exports=Ug?Ki.bind(Ki):function(){return Ki.apply(Ki,arguments)}});var Ji=f((PR,il)=>{"use strict";il.exports={}});var Ue=f((kR,sl)=>{"use strict";var Os=Ji(),Bs=G(),Hg=F(),al=function(i){return Hg(i)?i:void 0};sl.exports=function(i,e){return arguments.length<2?al(Os[i])||al(Bs[i]):Os[i]&&Os[i][e]||Bs[i]&&Bs[i][e]}});var Tr=f((wR,nl)=>{"use strict";var jg=X();nl.exports=jg({}.isPrototypeOf)});var Ir=f((AR,ol)=>{"use strict";ol.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var _s=f((RR,hl)=>{"use strict";var pl=G(),Vs=Ir(),ul=pl.process,ll=pl.Deno,cl=ul&&ul.versions||ll&&ll.version,dl=cl&&cl.v8,ke,Xi;dl&&(ke=dl.split("."),Xi=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Xi&&Vs&&(ke=Vs.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Vs.match(/Chrome\/(\d+)/),ke&&(Xi=+ke[1])));hl.exports=Xi});var Ns=f((LR,ml)=>{"use strict";var fl=_s(),Gg=ce(),Yg=G(),Wg=Yg.String;ml.exports=!!Object.getOwnPropertySymbols&&!Gg(function(){var i=Symbol();return!Wg(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&fl&&fl<41})});var Fs=f(($R,bl)=>{"use strict";var Qg=Ns();bl.exports=Qg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qs=f((CR,gl)=>{"use strict";var zg=Ue(),Kg=F(),Jg=Tr(),Xg=Fs(),Zg=Object;gl.exports=Xg?function(i){return typeof i=="symbol"}:function(i){var e=zg("Symbol");return Kg(e)&&Jg(e.prototype,Zg(i))}});var Er=f((DR,vl)=>{"use strict";var ev=String;vl.exports=function(i){try{return ev(i)}catch{return"Object"}}});var He=f((MR,Sl)=>{"use strict";var tv=F(),rv=Er(),iv=TypeError;Sl.exports=function(i){if(tv(i))return i;throw iv(rv(i)+" is not a function")}});var xr=f((OR,yl)=>{"use strict";var av=He(),sv=Ht();yl.exports=function(i,e){var t=i[e];return sv(t)?void 0:av(t)}});var Il=f((BR,Tl)=>{"use strict";var Us=Z(),Hs=F(),js=Be(),nv=TypeError;Tl.exports=function(i,e){var t,r;if(e==="string"&&Hs(t=i.toString)&&!js(r=Us(t,i))||Hs(t=i.valueOf)&&!js(r=Us(t,i))||e!=="string"&&Hs(t=i.toString)&&!js(r=Us(t,i)))return r;throw nv("Can't convert object to primitive value")}});var we=f((VR,El)=>{"use strict";El.exports=!0});var kl=f((_R,Pl)=>{"use strict";var xl=G(),ov=Object.defineProperty;Pl.exports=function(i,e){try{ov(xl,i,{value:e,configurable:!0,writable:!0})}catch{xl[i]=e}return e}});var Zi=f((NR,Al)=>{"use strict";var uv=G(),lv=kl(),wl="__core-js_shared__",cv=uv[wl]||lv(wl,{});Al.exports=cv});var Gs=f((FR,Ll)=>{"use strict";var dv=we(),Rl=Zi();(Ll.exports=function(i,e){return Rl[i]||(Rl[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:dv?"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 Pr=f((qR,$l)=>{"use strict";var pv=Wi(),hv=Object;$l.exports=function(i){return hv(pv(i))}});var Ae=f((UR,Cl)=>{"use strict";var fv=X(),mv=Pr(),bv=fv({}.hasOwnProperty);Cl.exports=Object.hasOwn||function(e,t){return bv(mv(e),t)}});var Ys=f((HR,Dl)=>{"use strict";var gv=X(),vv=0,Sv=Math.random(),yv=gv(1 .toString);Dl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+yv(++vv+Sv,36)}});var z=f((jR,Ol)=>{"use strict";var Tv=G(),Iv=Gs(),Ml=Ae(),Ev=Ys(),xv=Ns(),Pv=Fs(),Gt=Tv.Symbol,Ws=Iv("wks"),kv=Pv?Gt.for||Gt:Gt&&Gt.withoutSetter||Ev;Ol.exports=function(i){return Ml(Ws,i)||(Ws[i]=xv&&Ml(Gt,i)?Gt[i]:kv("Symbol."+i)),Ws[i]}});var Nl=f((GR,_l)=>{"use strict";var wv=Z(),Bl=Be(),Vl=qs(),Av=xr(),Rv=Il(),Lv=z(),$v=TypeError,Cv=Lv("toPrimitive");_l.exports=function(i,e){if(!Bl(i)||Vl(i))return i;var t=Av(i,Cv),r;if(t){if(e===void 0&&(e="default"),r=wv(t,i,e),!Bl(r)||Vl(r))return r;throw $v("Can't convert object to primitive value")}return e===void 0&&(e="number"),Rv(i,e)}});var ea=f((YR,Fl)=>{"use strict";var Dv=Nl(),Mv=qs();Fl.exports=function(i){var e=Dv(i,"string");return Mv(e)?e:e+""}});var St=f(Ul=>{"use strict";var Ov=Ve(),Bv=Ds(),Vv=Ms(),ta=Pe(),ql=ea(),_v=TypeError,Qs=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,zs="enumerable",Ks="configurable",Js="writable";Ul.f=Ov?Vv?function(e,t,r){if(ta(e),t=ql(t),ta(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Js in r&&!r[Js]){var a=Nv(e,t);a&&a[Js]&&(e[t]=r.value,r={configurable:Ks in r?r[Ks]:a[Ks],enumerable:zs in r?r[zs]:a[zs],writable:!1})}return Qs(e,t,r)}:Qs:function(e,t,r){if(ta(e),t=ql(t),ta(r),Bv)try{return Qs(e,t,r)}catch{}if("get"in r||"set"in r)throw _v("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var kr=f((QR,Hl)=>{"use strict";Hl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var yt=f((zR,jl)=>{"use strict";var Fv=Ve(),qv=St(),Uv=kr();jl.exports=Fv?function(i,e,t){return qv.f(i,e,Uv(1,t))}:function(i,e,t){return i[e]=t,i}});var ra=f((KR,Yl)=>{"use strict";var Hv=Gs(),jv=Ys(),Gl=Hv("keys");Yl.exports=function(i){return Gl[i]||(Gl[i]=jv(i))}});var ia=f((JR,Wl)=>{"use strict";Wl.exports={}});var tn=f((XR,Kl)=>{"use strict";var Gv=Yu(),zl=G(),Yv=Be(),Wv=yt(),Xs=Ae(),Zs=Zi(),Qv=ra(),zv=ia(),Ql="Object already initialized",en=zl.TypeError,Kv=zl.WeakMap,aa,wr,sa,Jv=function(i){return sa(i)?wr(i):aa(i,{})},Xv=function(i){return function(e){var t;if(!Yv(e)||(t=wr(e)).type!==i)throw en("Incompatible receiver, "+i+" required");return t}};Gv||Zs.state?(Re=Zs.state||(Zs.state=new Kv),Re.get=Re.get,Re.has=Re.has,Re.set=Re.set,aa=function(i,e){if(Re.has(i))throw en(Ql);return e.facade=i,Re.set(i,e),e},wr=function(i){return Re.get(i)||{}},sa=function(i){return Re.has(i)}):(Tt=Qv("state"),zv[Tt]=!0,aa=function(i,e){if(Xs(i,Tt))throw en(Ql);return e.facade=i,Wv(i,Tt,e),e},wr=function(i){return Xs(i,Tt)?i[Tt]:{}},sa=function(i){return Xs(i,Tt)});var Re,Tt;Kl.exports={set:aa,get:wr,has:sa,enforce:Jv,getterFor:Xv}});var rn=f((ZR,ec)=>{"use strict";var Zv=yr(),Zl=Function.prototype,Jl=Zl.apply,Xl=Zl.call;ec.exports=typeof Reflect=="object"&&Reflect.apply||(Zv?Xl.bind(Jl):function(){return Xl.apply(Jl,arguments)})});var an=f((eL,tc)=>{"use strict";var eS=Ut(),tS=X();tc.exports=function(i){if(eS(i)==="Function")return tS(i)}});var sc=f(ac=>{"use strict";var rc={}.propertyIsEnumerable,ic=Object.getOwnPropertyDescriptor,rS=ic&&!rc.call({1:2},1);ac.f=rS?function(e){var t=ic(this,e);return!!t&&t.enumerable}:rc});var sn=f(oc=>{"use strict";var iS=Ve(),aS=Z(),sS=sc(),nS=kr(),oS=jt(),uS=ea(),lS=Ae(),cS=Ds(),nc=Object.getOwnPropertyDescriptor;oc.f=iS?nc:function(e,t){if(e=oS(e),t=uS(t),cS)try{return nc(e,t)}catch{}if(lS(e,t))return nS(!aS(sS.f,e,t),e[t])}});var nn=f((iL,uc)=>{"use strict";var dS=ce(),pS=F(),hS=/#|\.prototype\./,Ar=function(i,e){var t=mS[fS(i)];return t==gS?!0:t==bS?!1:pS(e)?dS(e):!!e},fS=Ar.normalize=function(i){return String(i).replace(hS,".").toLowerCase()},mS=Ar.data={},bS=Ar.NATIVE="N",gS=Ar.POLYFILL="P";uc.exports=Ar});var Rr=f((aL,cc)=>{"use strict";var lc=an(),vS=He(),SS=yr(),yS=lc(lc.bind);cc.exports=function(i,e){return vS(i),e===void 0?i:SS?yS(i,e):function(){return i.apply(e,arguments)}}});var fe=f((sL,pc)=>{"use strict";var na=G(),TS=rn(),IS=an(),ES=F(),xS=sn().f,PS=nn(),Yt=Ji(),kS=Rr(),Wt=yt(),dc=Ae(),wS=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 TS(i,this,arguments)};return e.prototype=i.prototype,e};pc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?na:a?na[t]:(na[t]||{}).prototype,o=r?Yt:Yt[t]||Wt(Yt,t,{})[t],l=o.prototype,u,c,d,h,p,m,S,b,v;for(h in e)u=PS(r?h:t+(a?".":"#")+h,i.forced),c=!u&&n&&dc(n,h),m=o[h],c&&(i.dontCallGetSet?(v=xS(n,h),S=v&&v.value):S=n[h]),p=c&&S?S:e[h],!(c&&typeof m==typeof p)&&(i.bind&&c?b=kS(p,na):i.wrap&&c?b=wS(p):s&&ES(p)?b=IS(p):b=p,(i.sham||p&&p.sham||m&&m.sham)&&Wt(b,"sham",!0),Wt(o,h,b),s&&(d=t+"Prototype",dc(Yt,d)||Wt(Yt,d,{}),Wt(Yt[d],h,p),i.real&&l&&(u||!l[h])&&Wt(l,h,p)))}});var mc=f((nL,fc)=>{"use strict";var on=Ve(),AS=Ae(),hc=Function.prototype,RS=on&&Object.getOwnPropertyDescriptor,un=AS(hc,"name"),LS=un&&function(){}.name==="something",$S=un&&(!on||on&&RS(hc,"name").configurable);fc.exports={EXISTS:un,PROPER:LS,CONFIGURABLE:$S}});var gc=f((oL,bc)=>{"use strict";var CS=Math.ceil,DS=Math.floor;bc.exports=Math.trunc||function(e){var t=+e;return(t>0?DS:CS)(t)}});var oa=f((uL,vc)=>{"use strict";var MS=gc();vc.exports=function(i){var e=+i;return e!==e||e===0?0:MS(e)}});var yc=f((lL,Sc)=>{"use strict";var OS=oa(),BS=Math.max,VS=Math.min;Sc.exports=function(i,e){var t=OS(i);return t<0?BS(t+e,0):VS(t,e)}});var Ic=f((cL,Tc)=>{"use strict";var _S=oa(),NS=Math.min;Tc.exports=function(i){return i>0?NS(_S(i),9007199254740991):0}});var ua=f((dL,Ec)=>{"use strict";var FS=Ic();Ec.exports=function(i){return FS(i.length)}});var kc=f((pL,Pc)=>{"use strict";var qS=jt(),US=yc(),HS=ua(),xc=function(i){return function(e,t,r){var a=qS(e),s=HS(a),n=US(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}};Pc.exports={includes:xc(!0),indexOf:xc(!1)}});var Rc=f((hL,Ac)=>{"use strict";var jS=X(),ln=Ae(),GS=jt(),YS=kc().indexOf,WS=ia(),wc=jS([].push);Ac.exports=function(i,e){var t=GS(i),r=0,a=[],s;for(s in t)!ln(WS,s)&&ln(t,s)&&wc(a,s);for(;e.length>r;)ln(t,s=e[r++])&&(~YS(a,s)||wc(a,s));return a}});var cn=f((fL,Lc)=>{"use strict";Lc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Cc=f((mL,$c)=>{"use strict";var QS=Rc(),zS=cn();$c.exports=Object.keys||function(e){return QS(e,zS)}});var Mc=f(Dc=>{"use strict";var KS=Ve(),JS=Ms(),XS=St(),ZS=Pe(),ey=jt(),ty=Cc();Dc.f=KS&&!JS?Object.defineProperties:function(e,t){ZS(e);for(var r=ey(t),a=ty(t),s=a.length,n=0,o;s>n;)XS.f(e,o=a[n++],r[o]);return e}});var dn=f((gL,Oc)=>{"use strict";var ry=Ue();Oc.exports=ry("document","documentElement")});var mn=f((vL,Uc)=>{"use strict";var iy=Pe(),ay=Mc(),Bc=cn(),sy=ia(),ny=dn(),oy=zi(),uy=ra(),Vc=">",_c="<",hn="prototype",fn="script",Fc=uy("IE_PROTO"),pn=function(){},qc=function(i){return _c+fn+Vc+i+_c+"/"+fn+Vc},Nc=function(i){i.write(qc("")),i.close();var e=i.parentWindow.Object;return i=null,e},ly=function(){var i=oy("iframe"),e="java"+fn+":",t;return i.style.display="none",ny.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(qc("document.F=Object")),t.close(),t.F},la,ca=function(){try{la=new ActiveXObject("htmlfile")}catch{}ca=typeof document<"u"?document.domain&&la?Nc(la):ly():Nc(la);for(var i=Bc.length;i--;)delete ca[hn][Bc[i]];return ca()};sy[Fc]=!0;Uc.exports=Object.create||function(e,t){var r;return e!==null?(pn[hn]=iy(e),r=new pn,pn[hn]=null,r[Fc]=e):r=ca(),t===void 0?r:ay.f(r,t)}});var jc=f((SL,Hc)=>{"use strict";var cy=ce();Hc.exports=!cy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var gn=f((yL,Yc)=>{"use strict";var dy=Ae(),py=F(),hy=Pr(),fy=ra(),my=jc(),Gc=fy("IE_PROTO"),bn=Object,by=bn.prototype;Yc.exports=my?bn.getPrototypeOf:function(i){var e=hy(i);if(dy(e,Gc))return e[Gc];var t=e.constructor;return py(t)&&e instanceof t?t.prototype:e instanceof bn?by:null}});var Qt=f((TL,Wc)=>{"use strict";var gy=yt();Wc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:gy(i,e,t),i}});var Tn=f((IL,Kc)=>{"use strict";var vy=ce(),Sy=F(),yy=Be(),Ty=mn(),Qc=gn(),Iy=Qt(),Ey=z(),xy=we(),yn=Ey("iterator"),zc=!1,je,vn,Sn;[].keys&&(Sn=[].keys(),"next"in Sn?(vn=Qc(Qc(Sn)),vn!==Object.prototype&&(je=vn)):zc=!0);var Py=!yy(je)||vy(function(){var i={};return je[yn].call(i)!==i});Py?je={}:xy&&(je=Ty(je));Sy(je[yn])||Iy(je,yn,function(){return this});Kc.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:zc}});var da=f((EL,Xc)=>{"use strict";var ky=z(),wy=ky("toStringTag"),Jc={};Jc[wy]="z";Xc.exports=String(Jc)==="[object z]"});var zt=f((xL,Zc)=>{"use strict";var Ay=da(),Ry=F(),pa=Ut(),Ly=z(),$y=Ly("toStringTag"),Cy=Object,Dy=pa(function(){return arguments}())=="Arguments",My=function(i,e){try{return i[e]}catch{}};Zc.exports=Ay?pa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=My(e=Cy(i),$y))=="string"?t:Dy?pa(e):(r=pa(e))=="Object"&&Ry(e.callee)?"Arguments":r}});var td=f((PL,ed)=>{"use strict";var Oy=da(),By=zt();ed.exports=Oy?{}.toString:function(){return"[object "+By(this)+"]"}});var ha=f((kL,id)=>{"use strict";var Vy=da(),_y=St().f,Ny=yt(),Fy=Ae(),qy=td(),Uy=z(),rd=Uy("toStringTag");id.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;Fy(a,rd)||_y(a,rd,{configurable:!0,value:e}),r&&!Vy&&Ny(a,"toString",qy)}}});var sd=f((wL,ad)=>{"use strict";var Hy=Tn().IteratorPrototype,jy=mn(),Gy=kr(),Yy=ha(),Wy=vt(),Qy=function(){return this};ad.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=jy(Hy,{next:Gy(+!r,t)}),Yy(i,a,!1,!0),Wy[a]=Qy,i}});var od=f((AL,nd)=>{"use strict";var zy=X(),Ky=He();nd.exports=function(i,e,t){try{return zy(Ky(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var ld=f((RL,ud)=>{"use strict";var Jy=F(),Xy=String,Zy=TypeError;ud.exports=function(i){if(typeof i=="object"||Jy(i))return i;throw Zy("Can't set "+Xy(i)+" as a prototype")}});var In=f((LL,cd)=>{"use strict";var eT=od(),tT=Pe(),rT=ld();cd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=eT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return tT(a),rT(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Td=f(($L,yd)=>{"use strict";var iT=fe(),aT=Z(),fa=we(),vd=mc(),sT=F(),nT=sd(),dd=gn(),pd=In(),oT=ha(),uT=yt(),En=Qt(),lT=z(),hd=vt(),Sd=Tn(),cT=vd.PROPER,dT=vd.CONFIGURABLE,fd=Sd.IteratorPrototype,ma=Sd.BUGGY_SAFARI_ITERATORS,Lr=lT("iterator"),md="keys",$r="values",bd="entries",gd=function(){return this};yd.exports=function(i,e,t,r,a,s,n){nT(t,e,r);var o=function(v){if(v===a&&h)return h;if(!ma&&v in c)return c[v];switch(v){case md:return function(){return new t(this,v)};case $r:return function(){return new t(this,v)};case bd:return function(){return new t(this,v)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Lr]||c["@@iterator"]||a&&c[a],h=!ma&&d||o(a),p=e=="Array"&&c.entries||d,m,S,b;if(p&&(m=dd(p.call(new i)),m!==Object.prototype&&m.next&&(!fa&&dd(m)!==fd&&(pd?pd(m,fd):sT(m[Lr])||En(m,Lr,gd)),oT(m,l,!0,!0),fa&&(hd[l]=gd))),cT&&a==$r&&d&&d.name!==$r&&(!fa&&dT?uT(c,"name",$r):(u=!0,h=function(){return aT(d,this)})),a)if(S={values:o($r),keys:s?h:o(md),entries:o(bd)},n)for(b in S)(ma||u||!(b in c))&&En(c,b,S[b]);else iT({target:e,proto:!0,forced:ma||u},S);return(!fa||n)&&c[Lr]!==h&&En(c,Lr,h,{name:a}),hd[e]=h,S}});var Ed=f((CL,Id)=>{"use strict";Id.exports=function(i,e){return{value:i,done:e}}});var Pn=f((DL,Ad)=>{"use strict";var pT=jt(),xn=Rs(),xd=vt(),kd=tn(),hT=St().f,fT=Td(),ba=Ed(),mT=we(),bT=Ve(),wd="Array Iterator",gT=kd.set,vT=kd.getterFor(wd);Ad.exports=fT(Array,"Array",function(i,e){gT(this,{type:wd,target:pT(i),index:0,kind:e})},function(){var i=vT(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,ba(void 0,!0)):t=="keys"?ba(r,!1):t=="values"?ba(e[r],!1):ba([r,e[r]],!1)},"values");var Pd=xd.Arguments=xd.Array;xn("keys");xn("values");xn("entries");if(!mT&&bT&&Pd.name!=="values")try{hT(Pd,"name",{value:"values"})}catch{}});var Ld=f((ML,Rd)=>{"use strict";var ST=z(),yT=vt(),TT=ST("iterator"),IT=Array.prototype;Rd.exports=function(i){return i!==void 0&&(yT.Array===i||IT[TT]===i)}});var kn=f((OL,Cd)=>{"use strict";var ET=zt(),$d=xr(),xT=Ht(),PT=vt(),kT=z(),wT=kT("iterator");Cd.exports=function(i){if(!xT(i))return $d(i,wT)||$d(i,"@@iterator")||PT[ET(i)]}});var Md=f((BL,Dd)=>{"use strict";var AT=Z(),RT=He(),LT=Pe(),$T=Er(),CT=kn(),DT=TypeError;Dd.exports=function(i,e){var t=arguments.length<2?CT(i):e;if(RT(t))return LT(AT(t,i));throw DT($T(i)+" is not iterable")}});var Vd=f((VL,Bd)=>{"use strict";var MT=Z(),Od=Pe(),OT=xr();Bd.exports=function(i,e,t){var r,a;Od(i);try{if(r=OT(i,"return"),!r){if(e==="throw")throw t;return t}r=MT(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Od(r),t}});var va=f((_L,qd)=>{"use strict";var BT=Rr(),VT=Z(),_T=Pe(),NT=Er(),FT=Ld(),qT=ua(),_d=Tr(),UT=Md(),HT=kn(),Nd=Vd(),jT=TypeError,ga=function(i,e){this.stopped=i,this.result=e},Fd=ga.prototype;qd.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),l=BT(e,r),u,c,d,h,p,m,S,b=function(g){return u&&Nd(u,"normal",g),new ga(!0,g)},v=function(g){return a?(_T(g),o?l(g[0],g[1],b):l(g[0],g[1])):o?l(g,b):l(g)};if(s)u=i.iterator;else if(n)u=i;else{if(c=HT(i),!c)throw jT(NT(i)+" is not iterable");if(FT(c)){for(d=0,h=qT(i);h>d;d++)if(p=v(i[d]),p&&_d(Fd,p))return p;return new ga(!1)}u=UT(i,c)}for(m=s?i.next:u.next;!(S=VT(m,u)).done;){try{p=v(S.value)}catch(g){Nd(u,"throw",g)}if(typeof p=="object"&&p&&_d(Fd,p))return p}return new ga(!1)}});var Hd=f((NL,Ud)=>{"use strict";var GT=ea(),YT=St(),WT=kr();Ud.exports=function(i,e,t){var r=GT(e);r in i?YT.f(i,r,WT(0,t)):i[r]=t}});var jd=f(()=>{"use strict";var QT=fe(),zT=va(),KT=Hd();QT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zT(e,function(r,a){KT(t,r,a)},{AS_ENTRIES:!0}),t}})});var Yd=f((UL,Gd)=>{"use strict";Pn();jd();var JT=Ji();Gd.exports=JT.Object.fromEntries});var Qd=f((HL,Wd)=>{"use strict";Wd.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 Jd=f(()=>{"use strict";Pn();var XT=Qd(),ZT=G(),eI=zt(),tI=yt(),zd=vt(),rI=z(),Kd=rI("toStringTag");for(Sa in XT)wn=ZT[Sa],ya=wn&&wn.prototype,ya&&eI(ya)!==Kd&&tI(ya,Kd,Sa),zd[Sa]=zd.Array;var wn,ya,Sa});var Zd=f((YL,Xd)=>{"use strict";var iI=Yd();Jd();Xd.exports=iI});var Ta=f((WL,ep)=>{"use strict";var aI=Zd();ep.exports=aI});var tp=f(()=>{"use strict"});var Cr=f((KL,rp)=>{"use strict";var sI=Ut();rp.exports=typeof process<"u"&&sI(process)=="process"});var ap=f((JL,ip)=>{"use strict";var nI=St();ip.exports=function(i,e,t){return nI.f(i,e,t)}});var op=f((XL,np)=>{"use strict";var oI=Ue(),uI=ap(),lI=z(),cI=Ve(),sp=lI("species");np.exports=function(i){var e=oI(i);cI&&e&&!e[sp]&&uI(e,sp,{configurable:!0,get:function(){return this}})}});var lp=f((ZL,up)=>{"use strict";var dI=Tr(),pI=TypeError;up.exports=function(i,e){if(dI(e,i))return i;throw pI("Incorrect invocation")}});var Rn=f((e$,cp)=>{"use strict";var hI=X(),fI=F(),An=Zi(),mI=hI(Function.toString);fI(An.inspectSource)||(An.inspectSource=function(i){return mI(i)});cp.exports=An.inspectSource});var bp=f((t$,mp)=>{"use strict";var bI=X(),gI=ce(),dp=F(),vI=zt(),SI=Ue(),yI=Rn(),pp=function(){},TI=[],hp=SI("Reflect","construct"),Ln=/^\s*(?:class|function)\b/,II=bI(Ln.exec),EI=!Ln.exec(pp),Dr=function(e){if(!dp(e))return!1;try{return hp(pp,TI,e),!0}catch{return!1}},fp=function(e){if(!dp(e))return!1;switch(vI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return EI||!!II(Ln,yI(e))}catch{return!0}};fp.sham=!0;mp.exports=!hp||gI(function(){var i;return Dr(Dr.call)||!Dr(Object)||!Dr(function(){i=!0})||i})?fp:Dr});var vp=f((r$,gp)=>{"use strict";var xI=bp(),PI=Er(),kI=TypeError;gp.exports=function(i){if(xI(i))return i;throw kI(PI(i)+" is not a constructor")}});var $n=f((i$,yp)=>{"use strict";var Sp=Pe(),wI=vp(),AI=Ht(),RI=z(),LI=RI("species");yp.exports=function(i,e){var t=Sp(i).constructor,r;return t===void 0||AI(r=Sp(t)[LI])?e:wI(r)}});var Ip=f((a$,Tp)=>{"use strict";var $I=X();Tp.exports=$I([].slice)});var xp=f((s$,Ep)=>{"use strict";var CI=TypeError;Ep.exports=function(i,e){if(i<e)throw CI("Not enough arguments");return i}});var Cn=f((n$,Pp)=>{"use strict";var DI=Ir();Pp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(DI)});var qn=f((o$,Mp)=>{"use strict";var de=G(),MI=rn(),OI=Rr(),kp=F(),BI=Ae(),Dp=ce(),wp=dn(),VI=Ip(),Ap=zi(),_I=xp(),NI=Cn(),FI=Cr(),_n=de.setImmediate,Nn=de.clearImmediate,qI=de.process,Dn=de.Dispatch,UI=de.Function,Rp=de.MessageChannel,HI=de.String,Mn=0,Mr={},Lp="onreadystatechange",Or,It,On,Bn;Dp(function(){Or=de.location});var Fn=function(i){if(BI(Mr,i)){var e=Mr[i];delete Mr[i],e()}},Vn=function(i){return function(){Fn(i)}},$p=function(i){Fn(i.data)},Cp=function(i){de.postMessage(HI(i),Or.protocol+"//"+Or.host)};(!_n||!Nn)&&(_n=function(e){_I(arguments.length,1);var t=kp(e)?e:UI(e),r=VI(arguments,1);return Mr[++Mn]=function(){MI(t,void 0,r)},It(Mn),Mn},Nn=function(e){delete Mr[e]},FI?It=function(i){qI.nextTick(Vn(i))}:Dn&&Dn.now?It=function(i){Dn.now(Vn(i))}:Rp&&!NI?(On=new Rp,Bn=On.port2,On.port1.onmessage=$p,It=OI(Bn.postMessage,Bn)):de.addEventListener&&kp(de.postMessage)&&!de.importScripts&&Or&&Or.protocol!=="file:"&&!Dp(Cp)?(It=Cp,de.addEventListener("message",$p,!1)):Lp in Ap("script")?It=function(i){wp.appendChild(Ap("script"))[Lp]=function(){wp.removeChild(this),Fn(i)}}:It=function(i){setTimeout(Vn(i),0)});Mp.exports={set:_n,clear:Nn}});var Un=f((u$,Bp)=>{"use strict";var Op=function(){this.head=null,this.tail=null};Op.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}}};Bp.exports=Op});var _p=f((l$,Vp)=>{"use strict";var jI=Ir();Vp.exports=/ipad|iphone|ipod/i.test(jI)&&typeof Pebble<"u"});var Fp=f((c$,Np)=>{"use strict";var GI=Ir();Np.exports=/web0s(?!.*chrome)/i.test(GI)});var Qp=f((d$,Wp)=>{"use strict";var Et=G(),qp=Rr(),YI=sn().f,Hn=qn().set,WI=Un(),QI=Cn(),zI=_p(),KI=Fp(),jn=Cr(),Up=Et.MutationObserver||Et.WebKitMutationObserver,Hp=Et.document,jp=Et.process,Ia=Et.Promise,Gp=YI(Et,"queueMicrotask"),Wn=Gp&&Gp.value,Kt,Gn,Yn,Ea,Yp;Wn||(Br=new WI,Vr=function(){var i,e;for(jn&&(i=jp.domain)&&i.exit();e=Br.get();)try{e()}catch(t){throw Br.head&&Kt(),t}i&&i.enter()},!QI&&!jn&&!KI&&Up&&Hp?(Gn=!0,Yn=Hp.createTextNode(""),new Up(Vr).observe(Yn,{characterData:!0}),Kt=function(){Yn.data=Gn=!Gn}):!zI&&Ia&&Ia.resolve?(Ea=Ia.resolve(void 0),Ea.constructor=Ia,Yp=qp(Ea.then,Ea),Kt=function(){Yp(Vr)}):jn?Kt=function(){jp.nextTick(Vr)}:(Hn=qp(Hn,Et),Kt=function(){Hn(Vr)}),Wn=function(i){Br.head||Kt(),Br.add(i)});var Br,Vr;Wp.exports=Wn});var Kp=f((p$,zp)=>{"use strict";zp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var xa=f((h$,Jp)=>{"use strict";Jp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var xt=f((f$,Xp)=>{"use strict";var JI=G();Xp.exports=JI.Promise});var Qn=f((m$,Zp)=>{"use strict";Zp.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var th=f((b$,eh)=>{"use strict";var XI=Qn(),ZI=Cr();eh.exports=!XI&&!ZI&&typeof window=="object"&&typeof document=="object"});var Jt=f((g$,ah)=>{"use strict";var eE=G(),_r=xt(),tE=F(),rE=nn(),iE=Rn(),aE=z(),sE=th(),nE=Qn(),oE=we(),zn=_s(),rh=_r&&_r.prototype,uE=aE("species"),Kn=!1,ih=tE(eE.PromiseRejectionEvent),lE=rE("Promise",function(){var i=iE(_r),e=i!==String(_r);if(!e&&zn===66||oE&&!(rh.catch&&rh.finally))return!0;if(!zn||zn<51||!/native code/.test(i)){var t=new _r(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[uE]=r,Kn=t.then(function(){})instanceof r,!Kn)return!0}return!e&&(sE||nE)&&!ih});ah.exports={CONSTRUCTOR:lE,REJECTION_EVENT:ih,SUBCLASSING:Kn}});var Xt=f((v$,nh)=>{"use strict";var sh=He(),cE=TypeError,dE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw cE("Bad Promise constructor");e=r,t=a}),this.resolve=sh(e),this.reject=sh(t)};nh.exports.f=function(i){return new dE(i)}});var Ph=f(()=>{"use strict";var pE=fe(),hE=we(),Aa=Cr(),it=G(),rr=Z(),oh=Qt(),uh=In(),fE=ha(),mE=op(),bE=He(),wa=F(),gE=Be(),vE=lp(),SE=$n(),hh=qn().set,to=Qp(),yE=Kp(),TE=xa(),IE=Un(),fh=tn(),Ra=xt(),ro=Jt(),mh=Xt(),La="Promise",bh=ro.CONSTRUCTOR,EE=ro.REJECTION_EVENT,xE=ro.SUBCLASSING,Jn=fh.getterFor(La),PE=fh.set,Zt=Ra&&Ra.prototype,Pt=Ra,Pa=Zt,gh=it.TypeError,Xn=it.document,io=it.process,Zn=mh.f,kE=Zn,wE=!!(Xn&&Xn.createEvent&&it.dispatchEvent),vh="unhandledrejection",AE="rejectionhandled",lh=0,Sh=1,RE=2,ao=1,yh=2,ka,ch,LE,dh,Th=function(i){var e;return gE(i)&&wa(e=i.then)?e:!1},Ih=function(i,e){var t=e.value,r=e.state==Sh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===yh&&CE(e),e.rejection=ao),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(gh("Promise-chain cycle")):(u=Th(l))?rr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Eh=function(i,e){i.notified||(i.notified=!0,to(function(){for(var t=i.reactions,r;r=t.get();)Ih(r,i);i.notified=!1,e&&!i.rejection&&$E(i)}))},xh=function(i,e,t){var r,a;wE?(r=Xn.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),it.dispatchEvent(r)):r={promise:e,reason:t},!EE&&(a=it["on"+i])?a(r):i===vh&&yE("Unhandled promise rejection",t)},$E=function(i){rr(hh,it,function(){var e=i.facade,t=i.value,r=ph(i),a;if(r&&(a=TE(function(){Aa?io.emit("unhandledRejection",t,e):xh(vh,e,t)}),i.rejection=Aa||ph(i)?yh:ao,a.error))throw a.value})},ph=function(i){return i.rejection!==ao&&!i.parent},CE=function(i){rr(hh,it,function(){var e=i.facade;Aa?io.emit("rejectionHandled",e):xh(AE,e,i.value)})},er=function(i,e,t){return function(r){i(e,r,t)}},tr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=RE,Eh(i,!0))},eo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw gh("Promise can't be resolved itself");var r=Th(e);r?to(function(){var a={done:!1};try{rr(r,e,er(eo,a,i),er(tr,a,i))}catch(s){tr(a,s,i)}}):(i.value=e,i.state=Sh,Eh(i,!1))}catch(a){tr({done:!1},a,i)}}};if(bh&&(Pt=function(e){vE(this,Pa),bE(e),rr(ka,this);var t=Jn(this);try{e(er(eo,t),er(tr,t))}catch(r){tr(t,r)}},Pa=Pt.prototype,ka=function(e){PE(this,{type:La,done:!1,notified:!1,parent:!1,reactions:new IE,rejection:!1,state:lh,value:void 0})},ka.prototype=oh(Pa,"then",function(e,t){var r=Jn(this),a=Zn(SE(this,Pt));return r.parent=!0,a.ok=wa(e)?e:!0,a.fail=wa(t)&&t,a.domain=Aa?io.domain:void 0,r.state==lh?r.reactions.add(a):to(function(){Ih(a,r)}),a.promise}),ch=function(){var i=new ka,e=Jn(i);this.promise=i,this.resolve=er(eo,e),this.reject=er(tr,e)},mh.f=Zn=function(i){return i===Pt||i===LE?new ch(i):kE(i)},!hE&&wa(Ra)&&Zt!==Object.prototype)){dh=Zt.then,xE||oh(Zt,"then",function(e,t){var r=this;return new Pt(function(a,s){rr(dh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Zt.constructor}catch{}uh&&uh(Zt,Pa)}pE({global:!0,constructor:!0,wrap:!0,forced:bh},{Promise:Pt});fE(Pt,La,!1,!0);mE(La)});var Lh=f((T$,Rh)=>{"use strict";var DE=z(),wh=DE("iterator"),Ah=!1;try{kh=0,so={next:function(){return{done:!!kh++}},return:function(){Ah=!0}},so[wh]=function(){return this},Array.from(so,function(){throw 2})}catch{}var kh,so;Rh.exports=function(i,e){if(!e&&!Ah)return!1;var t=!1;try{var r={};r[wh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var no=f((I$,$h)=>{"use strict";var ME=xt(),OE=Lh(),BE=Jt().CONSTRUCTOR;$h.exports=BE||!OE(function(i){ME.all(i).then(void 0,function(){})})});var Ch=f(()=>{"use strict";var VE=fe(),_E=Z(),NE=He(),FE=Xt(),qE=xa(),UE=va(),HE=no();VE({target:"Promise",stat:!0,forced:HE},{all:function(e){var t=this,r=FE.f(t),a=r.resolve,s=r.reject,n=qE(function(){var o=NE(t.resolve),l=[],u=0,c=1;UE(e,function(d){var h=u++,p=!1;c++,_E(o,t,d).then(function(m){p||(p=!0,l[h]=m,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var Mh=f(()=>{"use strict";var jE=fe(),GE=we(),YE=Jt().CONSTRUCTOR,uo=xt(),WE=Ue(),QE=F(),zE=Qt(),Dh=uo&&uo.prototype;jE({target:"Promise",proto:!0,forced:YE,real:!0},{catch:function(i){return this.then(void 0,i)}});!GE&&QE(uo)&&(oo=WE("Promise").prototype.catch,Dh.catch!==oo&&zE(Dh,"catch",oo,{unsafe:!0}));var oo});var Oh=f(()=>{"use strict";var KE=fe(),JE=Z(),XE=He(),ZE=Xt(),ex=xa(),tx=va(),rx=no();KE({target:"Promise",stat:!0,forced:rx},{race:function(e){var t=this,r=ZE.f(t),a=r.reject,s=ex(function(){var n=XE(t.resolve);tx(e,function(o){JE(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Bh=f(()=>{"use strict";var ix=fe(),ax=Z(),sx=Xt(),nx=Jt().CONSTRUCTOR;ix({target:"Promise",stat:!0,forced:nx},{reject:function(e){var t=sx.f(this);return ax(t.reject,void 0,e),t.promise}})});var lo=f(($$,Vh)=>{"use strict";var ox=Pe(),ux=Be(),lx=Xt();Vh.exports=function(i,e){if(ox(i),ux(e)&&e.constructor===i)return e;var t=lx.f(i),r=t.resolve;return r(e),t.promise}});var Fh=f(()=>{"use strict";var cx=fe(),dx=Ue(),_h=we(),px=xt(),Nh=Jt().CONSTRUCTOR,hx=lo(),fx=dx("Promise"),mx=_h&&!Nh;cx({target:"Promise",stat:!0,forced:_h||Nh},{resolve:function(e){return hx(mx&&this===fx?px:this,e)}})});var qh=f(()=>{"use strict";Ph();Ch();Mh();Oh();Bh();Fh()});var Gh=f(()=>{"use strict";var bx=fe(),gx=we(),$a=xt(),vx=ce(),Hh=Ue(),jh=F(),Sx=$n(),Uh=lo(),yx=Qt(),po=$a&&$a.prototype,Tx=!!$a&&vx(function(){po.finally.call({then:function(){}},function(){})});bx({target:"Promise",proto:!0,real:!0,forced:Tx},{finally:function(i){var e=Sx(this,Hh("Promise")),t=jh(i);return this.then(t?function(r){return Uh(e,i()).then(function(){return r})}:i,t?function(r){return Uh(e,i()).then(function(){throw r})}:i)}});!gx&&jh($a)&&(co=Hh("Promise").prototype.finally,po.finally!==co&&yx(po,"finally",co,{unsafe:!0}));var co});var Ca=f((_$,Yh)=>{"use strict";var Ix=Ue();Yh.exports=Ix});var Qh=f((N$,Wh)=>{"use strict";tp();qh();Gh();var Ex=Ca();Wh.exports=Ex("Promise","finally")});var Kh=f((F$,zh)=>{"use strict";var xx=Qh();zh.exports=xx});var Da=f((q$,Jh)=>{"use strict";var Px=Kh();Jh.exports=Px});var If=f(()=>{"use strict";var Jx=fe(),Xx=Pr(),Zx=ua(),eP=oa(),tP=Rs();Jx({target:"Array",proto:!0},{at:function(e){var t=Xx(this),r=Zx(t),a=eP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});tP("at")});var xf=f((KC,Ef)=>{"use strict";If();var rP=Ca();Ef.exports=rP("Array","at")});var kf=f((JC,Pf)=>{"use strict";var iP=xf();Pf.exports=iP});var Ba=f((XC,wf)=>{"use strict";var aP=kf();wf.exports=aP});var im=f(()=>{"use strict"});var am=f(()=>{"use strict"});var nm=f((_O,sm)=>{"use strict";var lk=Be(),ck=Ut(),dk=z(),pk=dk("match");sm.exports=function(i){var e;return lk(i)&&((e=i[pk])!==void 0?!!e:ck(i)=="RegExp")}});var um=f((NO,om)=>{"use strict";var hk=zt(),fk=String;om.exports=function(i){if(hk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return fk(i)}});var cm=f((FO,lm)=>{"use strict";var mk=Pe();lm.exports=function(){var i=mk(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 hm=f((qO,pm)=>{"use strict";var bk=Z(),gk=Ae(),vk=Tr(),Sk=cm(),dm=RegExp.prototype;pm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in dm)&&!gk(i,"flags")&&vk(dm,i)?bk(Sk,i):e}});var mm=f((UO,fm)=>{"use strict";var No=X(),yk=Pr(),Tk=Math.floor,Vo=No("".charAt),Ik=No("".replace),_o=No("".slice),Ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xk=/\$([$&'`]|\d{1,2})/g;fm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=xk;return a!==void 0&&(a=yk(a),l=Ek),Ik(s,l,function(u,c){var d;switch(Vo(c,0)){case"$":return"$";case"&":return i;case"`":return _o(e,0,t);case"'":return _o(e,n);case"<":d=a[_o(c,1,-1)];break;default:var h=+c;if(h===0)return u;if(h>o){var p=Tk(h/10);return p===0?u:p<=o?r[p-1]===void 0?Vo(c,1):r[p-1]+Vo(c,1):u}d=r[h-1]}return d===void 0?"":d})}});var ym=f(()=>{"use strict";var Pk=fe(),kk=Z(),Fo=X(),bm=Wi(),wk=F(),Ak=Ht(),Rk=nm(),lr=um(),Lk=xr(),$k=hm(),Ck=mm(),Dk=z(),Mk=we(),Ok=Dk("replace"),Bk=TypeError,Sm=Fo("".indexOf),Vk=Fo("".replace),gm=Fo("".slice),_k=Math.max,vm=function(i,e,t){return t>i.length?-1:e===""?t:Sm(i,e,t)};Pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=bm(this),a,s,n,o,l,u,c,d,h,p=0,m=0,S="";if(!Ak(e)){if(a=Rk(e),a&&(s=lr(bm($k(e))),!~Sm(s,"g")))throw Bk("`.replaceAll` does not allow non-global regexes");if(n=Lk(e,Ok),n)return kk(n,e,r,t);if(Mk&&a)return Vk(lr(r),e,t)}for(o=lr(r),l=lr(e),u=wk(t),u||(t=lr(t)),c=l.length,d=_k(1,c),p=vm(o,l,0);p!==-1;)h=u?lr(t(l,p,o)):Ck(l,o,p,[],void 0,t),S+=gm(o,m,p)+h,m=p+c,p=vm(o,l,p+d);return m<o.length&&(S+=gm(o,m)),S}})});var Im=f((GO,Tm)=>{"use strict";im();am();ym();var Nk=Ca();Tm.exports=Nk("String","replaceAll")});var xm=f((YO,Em)=>{"use strict";var Fk=Im();Em.exports=Fk});var km=f((WO,Pm)=>{"use strict";var qk=xm();Pm.exports=qk});var vu="__VERSION__";var le=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(le||{}),gt=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(gt||{});var ji=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ji||{}),Es=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Es||{});var xs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xs||{});import{assertNever as xu,assertNonNullable as og,isNonNullable as Gi,ValueSubject as Ps,Subject as ug,Subscription as lg,merge as cg,observableFrom as dg,fromEvent as yu,map as Tu,tap as Iu,filterChanged as pg,isNullable as ks,ErrorCategory as Eu}from"@vkontakte/videoplayer-shared";var Su=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 Yi=class{constructor(e){this.connection$=new Ps(void 0);this.castState$=new Ps("NOT_AVAILABLE");this.errorEvent$=new ug;this.realCastState$=new Ps("NOT_AVAILABLE");this.subscription=new lg;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=Gi(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Su("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Eu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Gi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ks(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ks(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(yu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.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 xu(a.sessionState)}})).add(cg(yu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Iu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Tu(a=>a.castState)),dg([r.getCastState()])).pipe(pg(),Tu(hg),Iu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Gi(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();og(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(ks(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Gi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Eu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},hg=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 xu(i)}};var Db=Oe(Ta(),1);var uf=Oe(Da(),1);import{assertNever as Xh}from"@vkontakte/videoplayer-shared";var K=(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:Xh(t)}return i},ho=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Xh(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as kx,Subject as Ma,merge as Zh}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ma;this.transitionEnded$=new Ma;this.transitionUpdated$=new Ma;this.forceChanged$=new Ma;this.stateChangeStarted$=Zh(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Zh(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||kx(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}};import{assertNever as wx}from"@vkontakte/videoplayer-shared";var ef=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 wx(i)}};import{assertNever as ir,assertNonNullable as kt,debounce as tf,ErrorCategory as rf,fromEvent as wt,isNonNullable as af,map as sf,merge as nf,observableFrom as Ax,Subject as Rx,Subscription as fo,timeout as Lx,getHighestQuality as $x}from"@vkontakte/videoplayer-shared";var Cx=5,Dx=5,Mx=500,of=7e3,Nr=class{constructor(e){this.subscription=new fo;this.loadMediaTimeoutSubscription=new fo;this.videoState=new L("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?.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:ir(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:ir(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:ir(e)}break}default:ir(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ef(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 fo;this.subscription.add(e),this.subscription.add(nf(this.videoState.stateChangeStarted$.pipe(sf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(sf(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 Rx;e.add(a.pipe(tf(Mx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(wt(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)>Cx)&&a.next(o),s=o})),e.add(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(wt(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(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Dx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:ir(n)}}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=nf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ax(["init"])).pipe(tf(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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];kt(u);let c=$x(Object.keys(u));kt(c);let d=u[c];kt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];kt(u),r=u.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 u=t[e];kt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];kt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];kt(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:rf.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return ir(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return af(o)&&(n.metadata.title=o),af(l)&&(n.metadata.subtitle=l),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(Lx(of).subscribe(()=>s(`timeout(${of})`)))});(0,uf.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:rf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Fr=i=>{i.removeAttribute("src"),i.load()};var lf=i=>{try{i.pause(),i.playbackRate=0,Fr(i),i.remove()}catch(e){console.error(e)}};var mo=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)}},bo=window.WeakMap?new WeakMap:new mo,ee=i=>{let e=i.querySelector("video"),t=!!e;return e?Fr(e):(e=document.createElement("video"),i.appendChild(e)),bo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},te=i=>{let e=bo.get(i);bo.delete(i),e?Fr(i):lf(i)};import{assertNonNullable as qr,isNonNullable as Ne,isNullable as Vx,fromEvent as ar,merge as cf,observableFrom as df,filterChanged as pf,map as Ur,Subject as hf,Subscription as _x,ValueSubject as Nx,ErrorCategory as Fx}from"@vkontakte/videoplayer-shared";import{isNonNullable as go,isNullable as Ox,Subscription as Bx}from"@vkontakte/videoplayer-shared";var Oa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=Ox(a),u=new Bx;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},_e=(i,e,t)=>Oa(e,()=>i.loop,r=>{go(r)&&(i.loop=r)},{onError:t}),re=(i,e,t,r)=>Oa(e,()=>({muted:i.muted,volume:i.volume}),a=>{go(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),me=(i,e,t,r)=>Oa(e,()=>i.playbackRate,a=>{go(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),at=Oa;var qx=i=>["__",i.language,i.label].join("|"),Ux=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},vo=class i{constructor(){this.available$=new hf;this.current$=new Nx(void 0);this.error$=new hf;this.subscription=new _x;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:Fx.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(at(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ne(s)&&this.setInternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(at(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ne(s)&&this.setExternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(at(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(at(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qr(this.video);let{textTracks:e}=this.video;this.subscription.add(ar(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(cf(ar(e,"addtrack"),ar(e,"removetrack"),df(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),pf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(cf(ar(e,"change"),df(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ur(r=>r&&this.htmlTextTrackToITextTrack(r).id),pf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(ar(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(ar(e,"removetrack").subscribe(r=>{r.track?.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;Ne(t.align)&&(a.align=t.align),Ne(t.position)&&(a.position=t.position),Ne(t.size)&&(a.size=t.size),Ne(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){qr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:qx(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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){qr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Vx(e)||!Ux(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){qr(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){qr(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)}},be=vo;var Ye=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 ff=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},So=i=>{let e=ff(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},mf=i=>{let e=ff(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ge,map as st,merge as gf,filterChanged as jx,isNonNullable as vf,Subject as Gx,filter as Sf,mapTo as yf,combine as Yx,once as Wx,ErrorCategory as Qx,ValueSubject as Tf,getCurrentBrowser as zx,CurrentClientBrowser as Kx}from"@vkontakte/videoplayer-shared";var Hx=3,bf=(i,e,t=Hx)=>{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 l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var ie=i=>{let e=w=>ge(i,w).pipe(yf(void 0)),r=gf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>ge(i,w))).pipe(st(w=>w.type==="ended"?i.readyState<2:i.readyState<3),jx()),a=gf(ge(i,"progress"),ge(i,"timeupdate")).pipe(st(()=>bf(i.buffered,i.currentTime))),n=zx().browser===Kx.Safari?Yx({play:e("play").pipe(Wx()),playing:e("playing")}).pipe(yf(void 0)):e("playing"),o=ge(i,"volumechange").pipe(st(()=>({muted:i.muted,volume:i.volume}))),l=ge(i,"ratechange").pipe(st(()=>i.playbackRate)),u=ge(i,"error").pipe(Sf(()=>!!(i.error||i.played.length)),st(()=>{let w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:Qx.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=ge(i,"timeupdate").pipe(st(()=>i.currentTime)),d=new Gx,h=.3,p;c.subscribe(w=>{i.loop&&vf(p)&&vf(w)&&p>=i.duration-h&&w<=h&&d.next(p),p=w});let m=ge(i,"enterpictureinpicture"),S=ge(i,"leavepictureinpicture"),b=new Tf(mf(i));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));let v=new Tf(So(i));return ge(i,"fullscreenchange").pipe(st(()=>So(i))).subscribe(v),{playing$:n,pause$:e("pause").pipe(Sf(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ge(i,"durationchange").pipe(st(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:b,inFullscreen$:v}};import{VideoQuality as nt}from"@vkontakte/videoplayer-shared";var ot=i=>{switch(i){case"mobile":return nt.Q_144P;case"lowest":return nt.Q_240P;case"low":return nt.Q_360P;case"sd":case"medium":return nt.Q_480P;case"hd":case"high":return nt.Q_720P;case"fullhd":case"full":return nt.Q_1080P;case"quadhd":case"quad":return nt.Q_1440P;case"ultrahd":case"ultra":return nt.Q_2160P}};var xo=Oe(Ba(),1);import{isNonNullable as ut,isNullable as To,now as Df,isHigher as Io,isHigherOrEqual as $f,isInvariantQuality as Cf,isLower as Eo,isLowerOrEqual as sP,videoSizeToQuality as nP,assertNotEmptyArray as oP}from"@vkontakte/videoplayer-shared";var yo=!1,We={},Af=i=>{yo=i},Rf=()=>{We={}},Lf=i=>{i(We)},Hr=(i,e)=>{yo&&(We.meta=We.meta??{},We.meta[i]=e)},J=class{constructor(e){this.name=e}next(e){if(!yo)return;We.series=We.series??{};let t=We.series[this.name]??[];t.push([Date.now(),e]),We.series[this.name]=t}};var uP=new J("best_bitrate"),lP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Va=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Df()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cP='Assertion "ABR Tracks is empty array" failed',dP=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{oP(i,cP);let h=r.usePixelRatio?window.devicePixelRatio??1:1,p=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},m=p&&nP(p),S=r.considerPlaybackRate&&ut(o)?o:1,b=i.filter(E=>!Cf(E.quality)).sort((E,x)=>Io(E.quality,x.quality)?-1:1),v=(0,xo.default)(b,-1)?.quality,g=(0,xo.default)(b,0)?.quality,w=To(a)||ut(a.min)&&ut(a.max)&&Eo(a.max,a.min)||ut(a.min)&&g&&Io(a.min,g)||ut(a.max)&&v&&Eo(a.max,v),y=S*lP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},$=b.filter(E=>(m?Eo(E.quality,m):!0)?(ut(t)&&isFinite(t)&&ut(E.bitrate)?t-s>=E.bitrate*y:!0)?r.lazyQualitySwitch&&ut(r.minBufferToSwitchUp)&&l&&!Cf(l.quality)&&(n??0)<r.minBufferToSwitchUp&&Io(E.quality,l.quality)?(I[E.quality]="Buffer",!1):!!c&&$f(E.quality,c)?(I[E.quality]="DroppedFramesLimit",!1):w||(To(a.max)||sP(E.quality,a.max))&&(To(a.min)||$f(E.quality,a.min))?!0:(I[E.quality]="FitsQualityLimits",!1):(I[E.quality]="FitsThroughput",!1):(I[E.quality]="FitsContainer",!1))[0];$&&$.bitrate&&uP.next($.bitrate);let A=$??b[Math.ceil((b.length-1)/2)]??i[0];A.quality!==u?.last?.quality&&d({message:`
7
7
  [available tracks]
8
- ${a.map(D=>`{ id: ${D.id}, quality: ${D.quality}, bitrate: ${D.bitrate} }`).join(`
8
+ ${i.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(i??{}).map(([D,I])=>`${D}: ${I}`).join(`
12
+ ${Object.entries(r??{}).map(([E,x])=>`${E}: ${x}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
- containerQualityLimit: ${S},
16
+ containerQualityLimit: ${m},
17
17
  throughput: ${t},
18
- reserve: ${r},
18
+ reserve: ${s},
19
19
  playbackRate: ${o},
20
- playbackRateFactor: ${w},
20
+ playbackRateFactor: ${S},
21
21
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${E},
23
- minBufferToSwitchUp: ${i.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${u},
25
- limitsAreInvalid: ${M},
26
- maxQualityLimit: ${s?.max},
27
- minQualityLimit: ${s?.min},
22
+ bitrateFactor: ${y},
23
+ minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
+ droppedVideoMaxQualityLimit: ${c},
25
+ limitsAreInvalid: ${w},
26
+ maxQualityLimit: ${a?.max},
27
+ minQualityLimit: ${a?.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(L).map(([D,I])=>`${D}: ${I}`).join(`
30
+ ${Object.entries(I).map(([E,x])=>`${E}: ${x}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${q?.quality}
34
- [selected track] ${U?.quality}
35
- `});const W=U&&c&&c.history[U.id]&&ae()-c.history[U.id]<=i.trackCooldown&&(!c.last||U.id!==c.last.id);if(U?.id&&c&&!W&&c.recordSelection(U),W&&c?.last){const D=c.last;return c?.recordSwitch(D),h({message:`
36
- [last selected] ${D?.quality}
37
- `}),D}return c?.recordSwitch(U),U};var qe=a=>new URL(a).hostname,H;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(H||(H={}));const Fi=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var gt=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!Fi(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return Fi(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function be(){return ae()}function ds(a){return be()-a}function Vi(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,d=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return d&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function da(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Kt(a,e,t,i){const s=window.XMLHttpRequest;let r,n,o,d=!1,c=0,u,h,p=!1,f="arraybuffer",S=7e3,w=2e3,y=()=>{if(d)return;v(u);const Y=ds(u);let ce;if(Y<w){ce=w-Y,setTimeout(y,ce);return}w*=2,w>S&&(w=S),n&&n.abort(),n=new s,J()};const k=Y=>(r=Y,I),_=Y=>(h=Y,I),M=()=>(f="json",I),E=()=>{if(!d){if(--c>=0){y(),i&&i();return}d=!0,h&&h(),t&&t()}},L=Y=>(p=Y,I),J=()=>{u=be(),n=new s,n.open("get",a);let Y=0,ce,fe=0;const Re=()=>(v(u),Math.max(u,Math.max(ce||0,fe||0)));if(r&&n.addEventListener("progress",B=>{const j=be();r.updateChunk&&B.loaded>Y&&(r.updateChunk(Re(),B.loaded-Y),Y=B.loaded,ce=j)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(d)return;v(n);const B=n.status;if(B>=200&&B<300){if(n.response.byteLength&&r){const j=n.response.byteLength-Y;j&&r.updateChunk&&r.updateChunk(Re(),j)}n.responseType==="json"&&!Object.values(n.response).length?E():(h&&h(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){const B=()=>{v(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(fe=be(),n.removeEventListener("readystatechange",B))};n.addEventListener("readystatechange",B)}return n.responseType=f,n.send(),I},I={withBitrateReporting:k,withParallel:L,withJSONResponse:M,withRetryCount:Y=>(c=Y,I),withRetryInterval:(Y,ce)=>(A(Y)&&(w=Y),A(ce)&&(S=ce),I),withTimeout:Y=>(o=Y,I),withFinally:_,send:J,abort:()=>{n&&(n.abort(),n=void 0),d=!0,h&&h()}};return I}const ua=100,ha=2e3,la=500;let fa=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-la;if(t-e>ha){let i=0,s=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)i+=r.end-r.start,s+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;i+=n;const d=r.bytes*n/o;s+=d,r.start=t,r.bytes-=d}}}if(s>0&&i>0){const r=s*8/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>ua&&(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 pa{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=be(),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)},r=d=>{e._complete=1,e._responseData=d,e._downloadTime=be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Kt(t,r,()=>s("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=be()}_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=be();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,s){const r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=r._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),r._finallyCB&&r._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(r,e)}},r._cb=t,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=n=>(r._finallyCB=n,r),r}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 jt=1e4,gi=3,ma=6e4,ga=10,Sa=1,ba=500;class ya{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new fa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Vi(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){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=Vi(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,r;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)r=this.manifest[o],!(this.maxAutoQuality&&r.video.height>this.maxAutoQuality)&&(r.bitrate<e&&n>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||A(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{da(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({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 pa(gi,jt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let r=!1,n=null,o=null,d=null,c=null,u=!1;const h=()=>{const E=r&&(!u||u===this.rep);return E||t("Not running!"),E},p=(E,L,J)=>{d&&d.abort(),d=Kt(this.urlResolver.resolve(E,!1),L,J,()=>this._retryCallback()).withTimeout(jt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(gi).withFinally(()=>{d=null}).send()},f=(E,L,J)=>{v(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),L,J,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=E=>{const L=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${L}=>${E}`),i.playbackRate=E)},w=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const J=be()-1e4;let q=0;for(let W=0;W<this.bufferStates.length;W++){const D=this.bufferStates[W];E=Math.min(E,D.buf),D.ts<J&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${E} drop=${q} jitter=${this.sourceJitter}`);let U=E-Sa;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?S(1.15):U>1?S(1.1):U>.3?S(1.05):S(1)}},k=E=>{let L;const J=()=>L&&L.start?L.start.length:0,q=B=>L.start[B]/1e3,U=B=>L.dur[B]/1e3,W=B=>L.fragIndex+B,D=(B,j)=>({chunkIdx:W(B),startTS:q(B),dur:U(B),discontinuity:j}),I=()=>{let B=0;if(L&&L.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=j;this.sourceJitter>1&&(he+=this.sourceJitter-1);let ve=L.dur.length-1;for(;ve>=0&&(he-=L.dur[ve],!(he<=0));--ve);B=Math.min(ve,L.dur.length-1-ue),B=Math.max(B,0)}return D(B,!0)},Y=B=>{const j=J();if(!(j<=0)){if(A(B)){for(let ue=0;ue<j;ue++)if(q(ue)>B)return D(ue)}return I()}},ce=B=>{const j=J(),ue=B?B.chunkIdx+1:0,he=ue-L.fragIndex;if(!(j<=0)){if(!B||he<0||he-j>ga)return t(`Resync: offset=${he} bChunks=${j} chunk=`+JSON.stringify(B)),I();if(!(he>=j))return D(ue-L.fragIndex,!1)}},fe=(B,j,ue)=>{c&&c.abort(),c=Kt(this.urlResolver.resolve(B,!0,this.lowLatency),j,ue,()=>this._retryCallback()).withTimeout(jt).withRetryCount(gi).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(B,j)=>{fe(E,ue=>{if(!h())return;L=ue;const he=!!L.lowLatency;he!==this.lowLatency&&w(he);let ve=0;for(let Xe=0;Xe<L.dur.length;++Xe)ve+=L.dur[Xe];ve>0&&(v(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/L.dur.length)),s({name:"index",zeroTime:L.zeroTime,shiftDuration:L.shiftDuration}),this.sourceJitter=L.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,L.jitter/1e3)):1,B(Y(j))},()=>this._handleNetworkError())},nextChunk:ce}},_=()=>{r=!1,o&&o.abort(),d&&d.abort(),c&&c.abort(),v(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:E=>{const{videoElement:L,logger:J}=this.params;let q=k(e.jidxUrl),U,W,D,I,Y=0,ce,fe,Re;const B=()=>{ce&&(clearTimeout(ce),ce=void 0);const X=Math.max(ba,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=Y+X,Ae=be(),Ie=Math.min(1e4,Ee-Ae);Y=Ae;const ze=()=>{c||h()&&q.seek(()=>{h()&&(Y=be(),j(),B())})};Ie>0?ce=window.setTimeout(()=>{this.paused?B():ze()},Ie):ze()},j=()=>{let X;for(;X=q.nextChunk(I);)I=X,di(X);const Ee=q.nextChunk(D);if(Ee){if(D&&Ee.discontinuity){J("Detected discontinuity; restarting playback"),this.paused?B():(_(),this._initPlayerWith(e));return}Xe(Ee)}else B()},ue=(X,Ee)=>{if(!h()||!this.sourceBuffer)return;let Ae,Ie,ze;const xt=ke=>{window.setTimeout(()=>{h()&&ue(X,Ee)},ke)};if(this.sourceBuffer.updating)J("Source buffer is updating; delaying appendBuffer"),xt(100);else{const ke=be(),Ke=L.currentTime;!this.paused&&L.buffered.length>1&&fe===Ke&&ke-Re>500&&(J("Stall suspected; trying to fix"),this._fixupStall()),fe!==Ke&&(fe=Ke,Re=ke);const Be=this._getBufferSizeSec();if(Be>30)J(`Buffered ${Be} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(X),this.videoPlayStarted?(this.bufferStates.push({ts:ke,buf:Be}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ne){if(Ne.name==="QuotaExceededError")J("QuotaExceededError; delaying appendBuffer"),ze=this.sourceBuffer.buffered.length,ze!==0&&(Ae=this.sourceBuffer.buffered.start(0),Ie=Ke,Ie-Ae>4&&this.sourceBuffer.remove(Ae,Ie-3)),xt(1e3);else throw Ne}}},he=()=>{W&&U&&(J([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(D)]),ue(W,function(){W=null,j()}))},ve=X=>e.fragUrlTemplate.replace("%%id%%",X.chunkIdx),Xe=X=>{h()&&f(ve(X),(Ee,Ae)=>{if(h()){if(Ae/=1e3,W=Ee,D=X,n=X.startTS,Ae){const Ie=Math.min(10,X.dur/Ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}he()}},()=>this._handleNetworkError())},di=X=>{h()&&(v(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(X),!1)))},Yt=X=>{h()&&(e.cachedHeader=X,ue(X,()=>{U=!0,he()}))};r=!0,q.seek(X=>{if(h()){if(Y=be(),!X){B();return}I=X,!Q(E)||X.startTS>E?Xe(X):(D=X,j())}},E),e.cachedHeader?Yt(e.cachedHeader):p(e.headerUrl,Yt,()=>this._handleNetworkError())},stop:_,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),A(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,v(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return A(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let p,f,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(f=this._getBufferSizeSec(),S=h/this.bitrate,f>10&&S>.8||f>15&&S>.5||f>20&&S>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}p=this._selectQuality(h),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${h}`)},r=(()=>({updateChunk:(p,f)=>{const S=be();if(this.chunkRateEstimator.addInterval(p,S,f)){const y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:S-p,speed:y}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let n=-1/0,o,d=!0;const c=()=>{let h=r.get();if(h&&o&&this.autoQuality){if(d&&h>o&&ds(n)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,p)=>{const f=r.updateChunk(h,p);return f&&c(),f},notifySwitch:h=>{const p=be();h<o&&(n=p),o=h}}}_fetchManifest(e,t,i){this.manifestRequest=Kt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(jt).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;gt(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(H.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,r=n=>{const o=[];return n?.length?(n.forEach((d,c)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=c,o.push(d))}),o.sort(function(d,c){return d.video&&c.video?c.video.height-d.video.height:c.bitrate-d.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=r(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ma))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class us{onDroopedVideoFramesLimit$=new x;subscription=new ee;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new x;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;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(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Mt(this.droppedFramesChecker.checkTime).pipe(oe(()=>this.playing),oe(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Ge(this.droppedFramesChecker.checkTime)),i=O(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!ut(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,s=t-this.prevDroppedVideoFrames,r=1-(i-s)/i;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&kt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[s])=>Jt(i,s)?-1:1)?.[0]?.[0];return 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}}const Ei=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,Dt=(a,e)=>new Li(t=>{if(!window.IntersectionObserver)return;const i={root:null},s=new IntersectionObserver((n,o)=>{n.forEach(d=>t.next(d.isIntersecting||Ei()))},{...i,...e});s.observe(a);const r=C(document,"visibilitychange").pipe(T(n=>!document.hidden||Ei())).subscribe(n=>t.next(n));return()=>{s.unobserve(a),r.unsubscribe}}),Ta=[H.PAUSED,H.PLAYING,H.READY],va=[H.PAUSED,H.PLAYING,H.READY];class Ea{subscription=new ee;video;videoState=new ne(H.STOPPED);dash;representations$=new g([]);textTracksManager=new it;droppedFramesManager=new us;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new xi;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:P.WTF,message:"DashLiveProvider internal logic error",thrown:s})};O(this.videoState.stateChangeStarted$.pipe(T(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(T(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(s)}`})}),this.video=lt(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(qe(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 i=mt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(T(s=>s.map(({track:r})=>r)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===G.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(de(),T(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(De({zeroTime:this.zeroTime$.pipe(oe(A)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:r})=>this.params.output.liveTime$.next(s+r*1e3),t)).add(Ht(this.video,this.params.desiredState.isLooped,t)).add(pt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Lt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Dt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const r=s&&Is(s);this.dash.setMaxAutoQuality(r),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case H.MANIFEST_READY:case H.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return V(s.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ce(["init"])).pipe(Ge(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),ft(this.video)}createLiveDashPlayer(){const e=new ya({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(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&A(t)?t:oi(e.map(({track:c})=>c),{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}),r=s?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(n||r!==o)&&this.setVideoTrack(s),d&&this.setAutoQuality(i),n||d||r!==o){const c=e.find(({track:u})=>u.id===r)?.representation;v(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;v(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();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===H.PAUSED,r=-e,n=r<=this.maxSeekBackTime$.getValue()?r:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Oe(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:P.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const r=s.name??s.index.toString(10),n=ni(s.name)??dt(s.video),o=s.bitrate/1e3,d={...s.video};if(!n)continue;const c={id:r,quality:n,bitrate:o,size:d};i.push({track:c,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),A(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(va.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==l.PAUSED&&r.state===G.Requested&&Ta.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Oe(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(i===l.PAUSED)this.videoState.setState(H.PAUSED);else if(i===l.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const d=s?.from;d&&d===l.READY&&this.dash.catchUp(),this.dash.play()}return;case H.PLAYING:i===l.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(i===l.PLAYING)if(this.videoState.startTransitionTo(H.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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(Oe(this.params.source.url,d))}return;default:return V(e)}}}var me;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(me||(me={}));var Ve;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(Ve||(Ve={}));var ti;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ti||(ti={}));var xe;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(xe||(xe={}));var N;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(N||(N={}));var wt;(function(a){a.MP4="mp4",a.WEBM="webm"})(wt||(wt={}));var ii;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ii||(ii={}));var se;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(se||(se={}));var _t=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,r=a.end(i)*1e3;s<=e&&e<=r&&(t=r)}return Math.max(t-e,0)};class Ui{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let s=0,r=i.length;s<r;s++)if(i[s].callback===t){i.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let s=0,r=i.length;s<r;s++){const n=i[s];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class hs extends Ui{constructor(){super(),this.listeners||Ui.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 ls=class{constructor(){Object.defineProperty(this,"signal",{value:new hs,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(ls.prototype[Symbol.toStringTag]="AbortController",hs.prototype[Symbol.toStringTag]="AbortSignal");function fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Aa(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=a;if(!fs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||s)&&(r=function(c,u){let h;u&&u.signal&&(h=u.signal,delete u.signal);const p=new t(c,u);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},r.prototype=t.prototype);const n=e;return{fetch:(d,c)=>{const u=r&&r.prototype.isPrototypeOf(d)?d.signal:c?c.signal:void 0;if(u){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(u.aborted)return Promise.reject(h);const p=new Promise((f,S)=>{u.addEventListener("abort",()=>S(h),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(d,c)])}return n(d,c)},Request:r}}const ci=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ps=ci?Aa({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Vt=ci?ps.fetch:window.fetch;ci?ps.Request:window.Request;const $t=ci?ls:window.AbortController;var Ai=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const ka=(a,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-s-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},$a=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Hi=$a?ka:window.requestIdleCallback,wa=16;let ms=!1;try{ms=Pi().browser===os.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=wa}catch(a){console.error(a)}class Pa{bufferFull$=new x;error$=new x;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const r={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let i;ms&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),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}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:P.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{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:P.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){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:V(t)}}}var Yi=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class we{source;boxParser;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];const i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;const s=this.size32?this.size32-8:void 0,r=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,r,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 gs extends we{}class La extends we{}class Da extends we{majorBrand;minorVersion;compatibleBrands;constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){const s=this.readString(4);this.compatibleBrands.push(s),i-=4}}}class xa extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ca extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ra extends we{data;constructor(e,t){super(e,t),this.data=this.content}}class Je extends we{version;flags;constructor(e,t){super(e,t);const i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}}class Ss extends Je{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;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 i=0;i<this.referenceCount;i++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const d=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:d,SAPDeltaTime:c})}}}class Ia extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ba extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var ct;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(ct||(ct={}));class Ma extends Je{stereoMode;constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=ct.MONOSCOPIC;break;case 1:this.stereoMode=ct.TOP_BOTTOM;break;case 2:this.stereoMode=ct.LEFT_RIGHT;break;case 3:this.stereoMode=ct.STEREO_CUSTOM;break;case 4:this.stereoMode=ct.RIGHT_LEFT;break}this.cursor+=1}}class _a extends Je{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Oa extends Je{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Na extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Fa extends Je{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;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 Va extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ua extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ha extends Je{sequenceNumber;constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class Ya extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ga extends Je{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;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 qa extends Je{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class za extends Je{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 ie;(function(a){a.FtypBox="ftyp",a.MoovBox="moov",a.MoofBox="moof",a.MdatBox="mdat",a.SidxBox="sidx",a.TrakBox="trak",a.MdiaBox="mdia",a.MfhdBox="mfhd",a.TkhdBox="tkhd",a.TrafBox="traf",a.TfhdBox="tfhd",a.TfdtBox="tfdt",a.TrunBox="trun",a.MinfBox="minf",a.Sv3dBox="sv3d",a.St3dBox="st3d",a.PrhdBox="prhd",a.ProjBox="proj",a.EquiBox="equi",a.UuidBox="uuid",a.UnknownBox="unknown"})(ie||(ie={}));const Wa={[ie.FtypBox]:Da,[ie.MoovBox]:xa,[ie.MoofBox]:Ca,[ie.MdatBox]:Ra,[ie.SidxBox]:Ss,[ie.TrakBox]:Ia,[ie.MdiaBox]:Na,[ie.MfhdBox]:Ha,[ie.TkhdBox]:Fa,[ie.TrafBox]:Ya,[ie.TfhdBox]:Ga,[ie.TfdtBox]:qa,[ie.TrunBox]:za,[ie.MinfBox]:Va,[ie.Sv3dBox]:Ba,[ie.St3dBox]:Ma,[ie.PrhdBox]:_a,[ie.ProjBox]:Ua,[ie.EquiBox]:Oa,[ie.UuidBox]:La,[ie.UnknownBox]:gs};class ht{options;constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let i=this.options.offset;for(;i<e.byteLength;)try{const r=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(r,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){const i=Wa[e];return i?new i(t,new ht):new gs(t,new ht)}}class Ri{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 Qa=new TextDecoder("ascii"),ja=a=>Qa.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Ja=a=>{const e=new Ss(a,new ht);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(r=>{if(r.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=r.subsegmentDuration/e.timescale*1e3,o={status:N.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+r.referencedSize-1}};return t+=n,i+=r.referencedSize,o})},Xa=(a,e)=>{const i=new ht().parse(a),s=new Ri(i),r=s.findAll("moof"),n=e?s.findAll("uuid"):s.findAll("mdat");if(!(n.length&&r.length))return null;const o=r[0],d=n[n.length-1],c=o.source.byteOffset,h=d.source.byteOffset-o.source.byteOffset+d.size;return new DataView(a.buffer,c,h)},Ka=(a,e)=>{const i=new ht().parse(a),r=new Ri(i).findAll("traf"),n=r[r.length-1].children.find(h=>h.type==="tfhd"),o=r[r.length-1].children.find(h=>h.type==="tfdt"),d=r[r.length-1].children.find(h=>h.type==="trun");let c=0;return d.sampleDuration.length?c=d.sampleDuration.reduce((h,p)=>h+p,0):c=n.defaultSampleDuration*d.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},Za=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ii.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ht().parse(a),s=new Ri(i);if(s.find("sv3d")){e.is3dVideo=!0;const n=s.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=s.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.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},er={validateData:ja,parseInit:Za,getIndexRange:()=>{},parseSegments:Ja,parseFeedableSegmentChunk:Xa,getSegmentEndTime:Ka};var b;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(b||(b={}));var $;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})($||($={}));const Gi={[b.EBML]:{type:$.Master},[b.EBMLVersion]:{type:$.UnsignedInteger},[b.EBMLReadVersion]:{type:$.UnsignedInteger},[b.EBMLMaxIDLength]:{type:$.UnsignedInteger},[b.EBMLMaxSizeLength]:{type:$.UnsignedInteger},[b.DocType]:{type:$.String},[b.DocTypeVersion]:{type:$.UnsignedInteger},[b.DocTypeReadVersion]:{type:$.UnsignedInteger},[b.Void]:{type:$.Binary},[b.Segment]:{type:$.Master},[b.SeekHead]:{type:$.Master},[b.Seek]:{type:$.Master},[b.SeekID]:{type:$.Binary},[b.SeekPosition]:{type:$.UnsignedInteger},[b.Info]:{type:$.Master},[b.TimestampScale]:{type:$.UnsignedInteger},[b.Duration]:{type:$.Float},[b.Tracks]:{type:$.Master},[b.TrackEntry]:{type:$.Master},[b.Video]:{type:$.Master},[b.Projection]:{type:$.Master},[b.ProjectionType]:{type:$.UnsignedInteger},[b.ProjectionPrivate]:{type:$.Master},[b.Chapters]:{type:$.Master},[b.Cluster]:{type:$.Master},[b.Timestamp]:{type:$.UnsignedInteger},[b.SilentTracks]:{type:$.Master},[b.SilentTrackNumber]:{type:$.UnsignedInteger},[b.Position]:{type:$.UnsignedInteger},[b.PrevSize]:{type:$.UnsignedInteger},[b.SimpleBlock]:{type:$.Binary},[b.BlockGroup]:{type:$.Master},[b.EncryptedBlock]:{type:$.Binary},[b.Attachments]:{type:$.Master},[b.Tags]:{type:$.Master},[b.Cues]:{type:$.Master},[b.CuePoint]:{type:$.Master},[b.CueTime]:{type:$.UnsignedInteger},[b.CueTrackPositions]:{type:$.Master},[b.CueTrack]:{type:$.UnsignedInteger},[b.CueClusterPosition]:{type:$.UnsignedInteger},[b.CueRelativePosition]:{type:$.UnsignedInteger},[b.CueDuration]:{type:$.UnsignedInteger},[b.CueBlockNumber]:{type:$.UnsignedInteger},[b.CueCodecState]:{type:$.UnsignedInteger},[b.CueReference]:{type:$.Master},[b.CueRefTime]:{type:$.UnsignedInteger}},bs=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=si(a,t),s=i in Gi,r=s?Gi[i].type:$.Binary,n=a.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const d=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,u=si(d),h=c*2**((o-1)*8)+u,p=t+o;let f;return p+h>a.byteLength?f=new DataView(a.buffer,a.byteOffset+p):f=new DataView(a.buffer,a.byteOffset+p,h),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:r,tagHeaderSize:p,tagSize:p+h,value:f,valueSize:h}},si=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(a,e)=>{switch(e){case $.SignedInteger:return a.getInt8(0);case $.UnsignedInteger:return si(a);case $.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case $.String:return new TextDecoder("ascii").decode(a);case $.UTF8:return new TextDecoder("utf-8").decode(a);case $.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case $.Master:return a;case $.Binary:return a;default:V(e)}},Pt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=bs(i);if(!e(s))return;s.type===$.Master&&Pt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},tr=a=>{if(a.getUint32(0)!==b.EBML)return!1;let e,t,i;const s=bs(a);return Pt(s.value,({tag:r,type:n,value:o})=>(r===b.EBMLReadVersion?e=He(o,n):r===b.DocType?t=He(o,n):r===b.DocTypeReadVersion&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ys=[b.Info,b.SeekHead,b.Tracks,b.TrackEntry,b.Video,b.Projection,b.ProjectionType,b.ProjectionPrivate,b.Chapters,b.Cluster,b.Cues,b.Attachments,b.Tags],ir=[b.Timestamp,b.SilentTracks,b.SilentTrackNumber,b.Position,b.PrevSize,b.SimpleBlock,b.BlockGroup,b.EncryptedBlock],sr=a=>{let e,t,i,s,r=!1,n=!1,o=!1,d,c,u=!1;const h=0;return Pt(a,({tag:p,type:f,value:S,valueSize:w})=>{if(p===b.SeekID){const y=He(S,f);c=si(y)}else p!==b.SeekPosition&&(c=void 0);return p===b.Segment?(e=S.byteOffset,t=S.byteOffset+w):p===b.Info?r=!0:p===b.SeekHead?n=!0:p===b.TimestampScale?i=He(S,f):p===b.Duration?s=He(S,f):p===b.SeekPosition&&c===b.Cues?d=He(S,f):p===b.Tracks?Pt(S,({tag:y,type:k,value:_})=>y===b.ProjectionType?(u=He(_,k)===1,!1):!0):r&&n&&ys.includes(p)&&(o=!0),!o}),v(e,"Failed to parse webm Segment start"),v(t,"Failed to parse webm Segment end"),v(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:u,stereoMode:h,projectionType:ii.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ar=a=>{if(Q(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},rr=(a,e)=>{let t=!1,i=!1;const s=o=>A(o.time)&&A(o.position),r=[];let n;return Pt(a,({tag:o,type:d,value:c})=>{switch(o){case b.Cues:t=!0;break;case b.CuePoint:n&&s(n)&&r.push(n),n={};break;case b.CueTime:n&&(n.time=He(c,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:n&&(n.position=He(c,d));break;default:t&&ys.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&r.push(n),r.map((o,d)=>{const{time:c,position:u}=o,h=r[d+1];return{status:N.NONE,time:{from:c,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},nr=a=>{let e=0,t=!1;try{Pt(a,i=>i.tag===b.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ir.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[b.SimpleBlock,b.BlockGroup,b.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},or={validateData:tr,parseInit:sr,getIndexRange:ar,parseSegments:rr,parseFeedableSegmentChunk:nr},cr=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)},qi=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const d=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(d)?0:d)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),s=i?.[1]==="-"?-1:1,r={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},vt=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,r]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,d)=>Q(r)?o:Q(d)?r:r.padStart(parseInt(d,10),"0"))}return t},dr=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},r=i.children[0],n=r.getElementsByTagName("Period")[0],o=r.querySelector("BaseURL")?.textContent?.trim()??"",d=n.children,c=r.getAttribute("type")==="dynamic",u=r.getAttribute("availabilityStartTime"),h=u?new Date(u).getTime():void 0;let p;const f=r.getAttribute("mediaPresentationDuration"),S=n.getAttribute("duration"),y=r.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=qi(f);else if(S){const E=qi(S);A(E)&&(p=E)}else y&&(p=parseInt(y,10));let k=0;const _=r.getAttribute("profiles")?.split(",")??[],M=_.includes(ti.WEBM_AS_IN_FFMPEG)||_.includes(ti.WEBM_AS_IN_SPEC)?wt.WEBM:wt.MP4;for(const E of d){const L=E.getAttribute("mimeType"),J=E.getAttribute("codecs"),q=E.getAttribute("contentType")??L?.split("/")[0],U=E.getAttribute("profiles")?.split(",")??[],W=E.querySelectorAll("Representation"),D=E.querySelector("SegmentTemplate");if(q===me.TEXT){for(const I of W){const Y=I.getAttribute("id")||"",ce=E.getAttribute("lang"),fe=E.getAttribute("label"),Re=I.querySelector("BaseURL")?.textContent?.trim()??"",B=new URL(Re||o,e).toString(),j=Y.includes("_auto");s[me.TEXT].push({id:Y,lang:ce,label:fe,isAuto:j,kind:me.TEXT,url:B})}continue}for(const I of W){const Y=I.getAttribute("mimeType")??L,ce=I.getAttribute("codecs")??J??"",fe=I.getAttribute("contentType")??Y?.split("/")[0]??q,Re=E.getAttribute("profiles")?.split(",")??[],B=parseInt(I.getAttribute("width")??"",10),j=parseInt(I.getAttribute("height")??"",10),ue=parseInt(I.getAttribute("bandwidth")??"",10)/1e3,he=I.getAttribute("frameRate")??"",ve=I.getAttribute("quality")??void 0,Xe=he?cr(he):void 0,di=I.getAttribute("id")??(k++).toString(10),Yt=fe==="video"?`${j}p`:fe==="audio"?`${ue}Kbps`:ce,X=`${di}@${Yt}`,Ee=I.querySelector("BaseURL")?.textContent?.trim()??"",Ae=new URL(Ee||o,e).toString(),Ie=[..._,...U,...Re];let ze;const xt=I.querySelector("SegmentBase"),ke=I.querySelector("SegmentTemplate")??D;if(xt){const Be=I.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,ui]=Be.split("-").map(St=>parseInt(St,10)),Ze={from:Ne,to:ui},Ct=I.querySelector("SegmentBase")?.getAttribute("indexRange"),[hi,Gt]=Ct?Ct.split("-").map(St=>parseInt(St,10)):[],Rt=Ct?{from:hi,to:Gt}:void 0;ze={type:xe.BYTE_RANGE,url:Ae,initRange:Ze,indexRange:Rt}}else if(ke){const Be={representationId:I.getAttribute("id")??void 0,bandwidth:I.getAttribute("bandwidth")??void 0},Ne=parseInt(ke.getAttribute("timescale")??"",10),ui=ke.getAttribute("initialization")??"",Ze=ke.getAttribute("media"),Ct=parseInt(ke.getAttribute("startNumber")??"",10)??1,hi=vt(ui,Be);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Gt=ke.querySelectorAll("SegmentTimeline S")??[],Rt=[];let St=0,li="",fi=0;if(Gt.length){let qt=Ct,Me=0;for(const bt of Gt){const Fe=parseInt(bt.getAttribute("d")??"",10),st=parseInt(bt.getAttribute("r")??"",10)||0,zt=parseInt(bt.getAttribute("t")??"",10);Me=Number.isFinite(zt)?zt:Me;const pi=Fe/Ne*1e3,Ps=Me/Ne*1e3;for(let Wt=0;Wt<st+1;Wt++){const Ls=vt(Ze,{...Be,segmentNumber:qt.toString(10),segmentTime:(Me+Wt*Fe).toString(10)}),Mi=(Ps??0)+Wt*pi,Ds=Mi+pi;qt++,Rt.push({time:{from:Mi,to:Ds},url:Ls})}Me+=(st+1)*Fe,St+=(st+1)*pi}fi=Me/Ne*1e3,li=vt(Ze,{...Be,segmentNumber:qt.toString(10),segmentTime:Me.toString(10)})}else if(A(p)){const Me=parseInt(ke.getAttribute("duration")??"",10)/Ne*1e3,bt=Math.ceil(p/Me);let Fe=0;for(let st=1;st<bt;st++){const zt=vt(Ze,{...Be,segmentNumber:st.toString(10),segmentTime:Fe.toString(10)});Rt.push({time:{from:Fe,to:Fe+Me},url:zt}),Fe+=Me}fi=Fe,li=vt(Ze,{...Be,segmentNumber:bt.toString(10),segmentTime:Fe.toString(10)})}const ws={time:{from:fi,to:1/0},url:li};ze={type:xe.TEMPLATE,baseUrl:Ae,segmentTemplateUrl:Ze,initUrl:hi,totalSegmentsDurationMs:St,segments:Rt,nextSegmentBeyondManifest:ws,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!fe||!Y)continue;const Ke={video:me.VIDEO,audio:me.AUDIO,text:me.TEXT}[fe];Ke&&s[Ke].push({id:X,kind:Ke,segmentReference:ze,profiles:Ie,duration:p,bitrate:ue,mime:Y,codecs:ce,width:B,height:j,fps:Xe,quality:ve})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,container:M,representations:s}},ur=({id:a,width:e,height:t,bitrate:i,fps:s,quality:r})=>{const n=(r?ni(r):void 0)??dt({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},hr=({id:a,bitrate:e})=>({id:a,bitrate:e}),lr=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},fr=({id:a,lang:e,label:t,url:i,isAuto:s})=>({id:a,url:i,isAuto:s,type:"internal",language:e,label:t}),zi=a=>"url"in a,yt=a=>a.type===xe.TEMPLATE,ki=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class Wi{currentSegmentLength$=new g(0);onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new x;gaps=[];subscription=new ee;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new $t;destroyAbortController=new $t;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;loadByteRangeSegmentsTimeoutId=0;constructor(e,t,i,s,{fetcher:r,tuning:n,getCurrentPosition:o,isActiveLowLatency:d,compatibilityMode:c=!1,manifest:u}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=d,this.isLive=!!u?.dynamic,this.container=i,i){case wt.MP4:this.containerParser=er;break;case wt.WEBM:this.containerParser=or;break;default:V(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=Te(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);v(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Pa(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:P.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Yi(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);const i=this.initData.get(t.id),s=this.segments.get(t.id),r=this.parsedInitData.get(t.id);v(i,"No init buffer for starting representation"),v(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(r))}.bind(this));switchTo=Te(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);v(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Q(s)||Q(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),v(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const r=this.getCurrentPosition();A(r)&&(this.isLive||(i.forEach(n=>n.status=N.NONE),this.pruneBuffer(r,1/0,!0)),this.maintain(r))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new $t,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(v(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next((s?.time.to??0)-(s?.time.from??0));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=_t(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&u>=s.time.to-e+100&&(r=h)}if(isFinite(this.bufferLimit)&&Yi(this.sourceBuffer.buffered)>=this.bufferLimit){const c=_t(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,r),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))c="high";else{const u=o.at(0);u&&u.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===N.FED&&!o.length&&_t(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=i.at(-1);d&&d.status===N.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const r of e)Math.trunc(r.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from+s}),i=r.time.to;A(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let r=0,n=t.length-1;do s.unshift(t[n]),r+=t[n].time.to-t[n].time.from,n--;while(r<i&&n>=0);return this.liveInitialAdditionalOffset=r-i,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=Te(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const d=e.find(h=>h.id===o);d&&this.representations.set(o,d);const c=this.representations.get(o);if(!c||!yt(c.segmentReference))return;const u=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,u)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);v(i);const s=this.segments.get(t);v(s,"No segments for starting representation");const r=this.initData.get(t);if(v(r,"No init buffer for starting representation"),!(r instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!yt(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:N.NONE,size:void 0})),s=this.segments.get(t.id)??[],r=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(r)>=Math.floor(o.time.from)&&Math.floor(r)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!yt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),r=vt(i.segmentTemplateUrl,{segmentTime:s}),n=this.segments.get(t.id)??[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||n.push({status:N.NONE,time:{from:e.segment.time.to,to:1/0},url:r})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(r=>r.time.from<=e&&r.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:h,time:{from:p,to:f}},S)=>{const w=p<=i&&f>=i,y=p>i||w||S===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),_=this.preloadOnly&&p<=i+k||f<=i+k;return(h===N.NONE||h===N.PARTIALLY_EJECTED&&y&&_&&this.sourceBuffer&&!Ai(this.sourceBuffer.buffered,i))&&y&&_});if(s===-1)return[];if(t!==xe.BYTE_RANGE)return e.slice(s,s+1);const r=e;let n=0,o=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<r.length&&(n<=c||o<=u);h++){const p=r[h];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status===N.NONE||p.status===N.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type===xe.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=N.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:r,url:n,signal:o,onProgress:d,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Te(o,async function*(){const u=Xt(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,u))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const u=await this.fetcher.fetch(n,{range:r,signal:o,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!u)return;const h=new DataView(u);if(this.isActiveLowLatency()){const p=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(h,p)}d&&s.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(h,o),s.segment.status=N.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(u){this.abortActiveSegments([e]),ki(u)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const d of e)d.status=N.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:r,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Te(n,async function*(){const d=Xt(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,d),C(window,"online").pipe(Se()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(r,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(d){this.abortActiveSegments(e),ki(d)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(yt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:r}=this.downloadAbortController;return{url:i,range:s,signal:r,onProgress:(o,d)=>{if(!r.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:d,signal:r,onSegmentAppendFailed:()=>this.abort(),globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:P.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!yt(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const s=i.toString(),{signal:r}=this.downloadAbortController,n=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,u)=>{if(!r.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:c,loaded:u,signal:r,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:P.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:s,signal:r,onProgress:d,onProgressTasks:n}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:r}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:d}=o;if(o.representationId===t){if(r.aborted){s();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),u=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);u?.byteLength&&(d.status=N.PARTIALLY_FED,o.feedingBytes+=u.byteLength,await this.sourceBufferTaskQueue.append(u),o.fedBytes+=u.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:r,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const d=o.segmentReference.type,c=e.byteLength;for(const u of this.activeSegments){const{segment:h}=u,p=d===xe.BYTE_RANGE,f=p?h.byte.to-h.byte.from+1:c;if(u.representationId!==t||!(!p||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(r.aborted){n();continue}const w=p?h.byte.from-i:0,y=p?h.byte.to-i:e.byteLength,k=w<s,_=y<=s;if(h.status===N.DOWNLOADING&&k&&_){h.status=N.DOWNLOADED;const M=new DataView(e.buffer,e.byteOffset+w,f);this.sourceBufferTaskQueue.append(M,r).then(E=>E&&!r.aborted?this.onSegmentFullyAppended(u,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(u.loadedBytes=Math.min(f,s-w),u.loadedBytes>u.feedingBytes)){const M=new DataView(e.buffer,e.byteOffset+w+u.feedingBytes,u.loadedBytes-u.feedingBytes),E=u.loadedBytes===f?M:this.containerParser.parseFeedableSegmentChunk(M);E?.byteLength&&(h.status=N.PARTIALLY_FED,u.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,r).then(L=>{if(r.aborted)n();else if(L)u.fedBytes+=E.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=N.FED,zi(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===N.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=N.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===N.PARTIALLY_FED||e.status===N.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=N.NONE),e.status=N.PARTIALLY_EJECTED):e.status=N.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Hi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Te(this.destroyAbortController.signal,async function*(){const o=Xt(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:d,dataView:c,segments:u}=o,h=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,h);let p=u;this.isLive&&yt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(e)||this.sourceBuffer.updating)return!1;let s=0,r=1/0,n=-1/0,o=!1;const d=c=>{r=Math.min(r,c.time.from),n=Math.max(n,c.time.to);const u=zi(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(const c of this.segments.values())for(const u of c){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;u.status===N.FED&&d(u)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const c of this.segments.values())for(const u of c){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;u.status===N.FED&&d(u)}}if(o=isFinite(r)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const u=this.sourceBuffer.buffered.start(c)*1e3,h=this.sourceBuffer.buffered.end(c)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===N.NONE&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(h)){r=u,n=h;break}}if(o=isFinite(r)&&isFinite(n),!o&&i){s=0,r=1/0,n=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const h of u)h.time.from>e+c&&h.status===N.FED&&d(h)}return o=isFinite(r)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(r,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){const n=this.sourceBuffer.buffered.start(r)*1e3,o=this.sourceBuffer.buffered.end(r)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(r=>s&&r.from===s.from&&r.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Hi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:P.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),r=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:r})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:r}=s;if(r!==N.FED&&r!==N.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),d=e.some(u=>u.from-t<=n&&u.to+t>=o),c=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);d||(c.length===1||this.gaps.some(u=>u.from===s.time.from||u.to===s.time.to)?s.status=N.PARTIALLY_EJECTED:s.status=N.NONE)}}}var $i=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},pr=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?Ti.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},At;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(At||(At={}));class mr{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new $t;subscription=new ee;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=pr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=Te(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=$i(t));const i=yield Vt(t,{signal:this.abortAllController.signal}).catch(It);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=Te(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?At.HEADER:At.PARAM,range:i,onProgress:s,priority:r="auto",signal:n,measureThroughput:o=!0,isLowLatency:d=!1}={}){let c=e;const u=new Headers;if(i)switch(t){case At.HEADER:{u.append("Range",`bytes=${i.from}-${i.to}`);break}case At.PARAM:{const U=new URL(c,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),c=U.toString();break}default:V(t)}this.requestQuic&&(c=$i(c));let h=this.abortAllController.signal,p;if(n){const U=new $t;if(p=O(C(this.abortAllController.signal,"abort"),C(n,"abort")).subscribe(()=>{try{U.abort()}catch(W){It(W)}}),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(W){It(W)}h=U.signal}const f=ae(),S=yield Vt(c,{priority:r,headers:u,signal:h}).catch(It),w=ae();if(!S)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(w-f),!S.ok||!S.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));if(this.onHeadersReceived(S.headers),!s&&!o)return p?.unsubscribe(),S.arrayBuffer();const[y,k]=S.body.tee(),_=y.getReader();o&&this.throughputEstimator?.trackStream(k,d);let M=0,E=new Uint8Array(0),L=!1;const J=U=>{p?.unsubscribe(),L=!0,It(U)},q=Te(h,async function*({done:U,value:W}){if(M===0&&this.lastRequestFirstBytes$.next(ae()-f),h.aborted){p?.unsubscribe();return}if(!U&&W){const D=new Uint8Array(E.length+W.length);D.set(E),D.set(W,E.length),E=D,M+=W.byteLength,s?.(new DataView(E.buffer),M),yield _?.read().then(q,J)}}.bind(this));return yield _?.read().then(q,J),p?.unsubscribe(),L?null:E.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case xe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case xe.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:V(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=Te(this.abortAllController.signal,async function*(e,t,i){if(e.type!==xe.BYTE_RANGE)return null;const{from:s,to:r}=e.initRange;let n=s,o=r,d=!1,c,u;e.indexRange&&(c=e.indexRange.from,u=e.indexRange.to,d=r+1===c,d&&(n=Math.min(c,s),o=Math.max(u,r))),n=Math.min(n,0);const h=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!h)return null;const p=new DataView(h,s-n,r-n+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),S=e.indexRange??t.getIndexRange(f);if(!S)throw new ReferenceError("No way to load representation index");let w;if(d)w=new DataView(h,S.from-n,S.to-S.from+1);else{const k=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!k)return null;w=new DataView(k)}const y=t.parseSegments(w,f,S);return{init:f,dataView:new DataView(h),segments:y}}.bind(this));fetchTemplateRepresentation=Te(this.abortAllController.signal,async function*(e,t){if(e.type!==xe.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:N.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const It=a=>{if(!ki(a))throw a},Et=1e3,ai=(a,e,t)=>t*e+(1-t)*a,Ts=(a,e)=>a.reduce((t,i)=>t+i,0)/e,gr=(a,e,t,i)=>{let s=0,r=t;const n=Ts(a,e),o=e<i?e:i;for(let d=0;d<o;d++)a[r]>n?s++:s--,r=(a.length+r-1)%a.length;return Math.abs(s)===o};class Ii{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new g(e.initial),this.debounced$=new g(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ue(`raw_${t}`),this.smoothedSeries$=new Ue(`smoothed_${t}`),this.reportedSeries$=new Ue(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),r=this.smoothed+this.params.deviationFactor*s,n=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>r||this.smoothed<n)&&(Q(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 Sr extends Ii{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ai(this.slow,e,this.params.emaAlphaSlow),this.fast=ai(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class br extends Ii{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Ts(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ai(this.emaSmoothed,e,this.params.emaAlpha);const i=gr(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class yr extends Ii{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),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?ai(this.smoothed,e,this.params.emaAlpha):e}}class wi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Sr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new br({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new yr({initial:e,label:"liveEdgeDelay",...t})}}const Tr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},at=()=>window.ManagedMediaSource||window.MediaSource,vs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),vr=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Er=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,Qi=["timeupdate","progress","play","seeked","stalled","waiting"];var Le;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Le||(Le={}));let Ar=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new ee;representationSubscription=new ee;fetcher;state$=new ne(Le.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);currentVideoSegmentLength$=new g(0);currentAudioSegmentLength$=new g(0);error$=new x;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);isLive$=new g(!1);liveDuration$=new g(0);liveAvailabilityStartTime$=new g(void 0);bufferLength$=new g(0);liveLoadBufferLength$=new g(0);livePositionFromPlayer$=new g(0);liveEstimatedDelay;timeInWaiting=0;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new x;gapWatchdogStarted=!1;gapWatchdogSubscription;stallWatchdogSubscription;destroyController=new $t;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new mr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=wi.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=Te(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Oe(t,i,le.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:P.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=Te(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:P.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=dr(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:P.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:r,codecs:n})=>!!(this.element?.canPlayType?.(r)&&at()?.isTypeSupported?.(`${r}; codecs="${n}"`)||s===me.TEXT);return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,r])=>[s,r.filter(i)]))}}.bind(this));async seekLive(e){v(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=Oe(this.manifestUrlString,t,le.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=Te(this.destroyController.signal,async function*(e,t,i){v(this.manifest),v(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Le.REPRESENTATIOS_READY);const s=f=>{this.representationSubscription.add(C(f,"error").pipe(oe(S=>!!this.element?.played.length)).subscribe(S=>{this.error$.next({id:"VideoSource",category:P.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:S})}))};this.source=this.tuning.useManagedMediaSource?Er():new MediaSource;const r=document.createElement("source");if(s(r),r.src=URL.createObjectURL(this.source),this.element.appendChild(r),this.tuning.useManagedMediaSource&&vs())if(i){const f=document.createElement("source");s(f),f.type="application/x-mpegurl",f.src=i.url,this.element.appendChild(f)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const 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 Wi(me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],A(t)&&(this.audioBufferManager=new Wi(me.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(Mt(Et).subscribe(f=>{if(this.element?.paused){const S=_i(this.manifestUrlString,le.DASH_CMAF_OFFSET_P);this.manifestUrlString=Oe(this.manifestUrlString,S+Et,le.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...Qi.filter(f=>f!=="waiting").map(f=>C(this.element,f))).pipe(T(f=>this.element?_t(this.element.buffered,this.element.currentTime*1e3):0),de(),oe(f=>!!f),Ft(f=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(oe(S=>this.isActiveLowLatency&&!!S)).subscribe(S=>this.liveEstimatedDelay.next(S))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(S=>{if(!this.isActiveLowLatency)return;const w=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,k=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,_=S-w;let M=1+Math.sign(_)*k;Math.abs(_)<y?M=1:Math.abs(_)>y*2&&(M=1+Math.sign(_)*k*2),Tr(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(S=>{let w=0;if(S){const y=(this.element?.currentTime??0)*1e3;w=Math.min(...this.bufferManagers.map(_=>_.getLiveSegmentsToLoadState(this.manifest)?.to??y))-y}this.liveLoadBufferLength$.getValue()!==w&&this.liveLoadBufferLength$.next(w)}));let f=0;this.representationSubscription.add(De({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Bs(Et)).subscribe(async({liveLoadBufferLength:S,bufferLength:w})=>{if(v(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,k=_i(this.manifestUrlString,le.DASH_CMAF_OFFSET_P),_=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,M=Math.min(_,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,L=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,J=this.isActiveLowLatency?w:S;let q=Ve.None;if(this.isActiveLowLatency?q=Ve.ActiveLowLatency:J<M+L&&J>=M?q=Ve.LiveWithTargetOffset:k!==0&&J<M&&(q=Ve.LiveForwardBuffering),isFinite(S)&&(f=S>f?S:f),q===Ve.LiveForwardBuffering||q===Ve.LiveWithTargetOffset){const U=f-(M+E),W=this.normolizeLiveOffset(Math.trunc(k+U/y)),D=Math.abs(W-k);let I;!S||D<=this.tuning.dashCmafLive.offsetCalculationError?I=k:W>0&&D>this.tuning.dashCmafLive.offsetCalculationError?I=W:I=0,this.manifestUrlString=Oe(this.manifestUrlString,I,le.DASH_CMAF_OFFSET_P)}q!==Ve.None&&q!==Ve.ActiveLowLatency&&(f=0,this.updateLive())}))}const o=O(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe(T(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),d=O(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe(T(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,De({allBuffersFull:o,someBufferEnded:d}).pipe(oe(({allBuffersFull:f,someBufferEnded:S})=>f&&S))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{this.source?.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:P.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(O(...this.bufferManagers.map(f=>f.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(f=>this.source?.addEventListener("sourceopen",f)));const c=this.manifest.duration??0,u=(f,S)=>Math.max(f,S.duration??0),h=this.manifest.representations.audio.reduce(u,c),p=this.manifest.representations.video.reduce(u,c);(h||p)&&(this.source.duration=Math.max(h,p)/1e3),this.audioBufferManager&&A(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){v(this.element),this.state$.setState(Le.RUNNING),this.subscription.add(O(...Qi.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:P.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ai(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const e=()=>{if(this.element){if(this.timeInWaiting+=Et,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Mt(Et).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:P.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{[me.VIDEO]:this.videoBufferManager,[me.AUDIO]:this.audioBufferManager,[me.TEXT]:null}[e]?.switchTo(t)}seek(e,t){v(this.element),v(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ai(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Le.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Mt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:P.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.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,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from-s<=t&&n.to+s>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i)+10;r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class kr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class $r{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,r=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:s,y:r,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*(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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var wr=`#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;}`,Pr=`#ifdef GL_ES
39
- precision highp float;precision highp int;
33
+ [best track] ${$?.quality}
34
+ [selected track] ${A?.quality}
35
+ `});let D=A&&u&&u.history[A.id]&&Df()-u.history[A.id]<=r.trackCooldown&&(!u.last||A.id!==u.last.id);if(A?.id&&u&&!D&&u.recordSelection(A),D&&u?.last){let E=u.last;return u?.recordSwitch(E),d({message:`
36
+ [last selected] ${E?.quality}
37
+ `}),E}return u?.recordSwitch(A),A},lt=dP;var Y=i=>new URL(i).hostname;import{assertNever as Nf,assertNonNullable as Ff,combine as $P,debounce as CP,ErrorCategory as qf,filter as DP,filterChanged as MP,isNonNullable as Ro,map as Ua,merge as Uf,observableFrom as OP,Subscription as BP,ValueSubject as Lo,videoQualityToHeight as VP,videoSizeToQuality as _P}from"@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=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Mf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Mf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Na,isNullable as fP,assertNonNullable as Yr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Of,assertNonNullable as _a,now as pP}from"@vkontakte/videoplayer-shared";function W(){return pP()}function Po(i){return W()-i}function ko(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,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_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 sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,h=!1,p="arraybuffer",m=7e3,S=2e3,b=()=>{if(l)return;_a(c);let R=Po(c),q;if(R<S){q=S-R,setTimeout(b,q);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new a,V()},v=R=>(s=R,x),g=R=>(d=R,x),w=()=>(p="json",x),y=()=>{if(!l){if(--u>=0){b(),r&&r();return}l=!0,d&&d(),t&&t()}},I=R=>(h=R,x),V=()=>{c=W(),n=new a,n.open("get",i);let R=0,q,Q=0,Te=()=>(_a(c),Math.max(c,Math.max(q||0,Q||0)));if(s&&n.addEventListener("progress",k=>{let O=W();s.updateChunk&&k.loaded>R&&(s.updateChunk(Te(),k.loaded-R),R=k.loaded,q=O)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(l)return;_a(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let O=n.response.byteLength-R;O&&s.updateChunk&&s.updateChunk(Te(),O)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),h){let k=()=>{_a(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=W(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),x},x={withBitrateReporting:v,withParallel:I,withJSONResponse:w,withRetryCount:R=>(u=R,x),withRetryInterval:(R,q)=>(Of(R)&&(S=R),Of(q)&&(m=q),x),withTimeout:R=>(o=R,x),withFinally:g,send:V,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return x}var jr=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 l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}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 Gr=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=W(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=W()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=sr(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=W()}_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=W();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 Fa=1e4,wo=3;var mP=6e4,bP=10,gP=1,vP=500,Wr=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 jr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ko(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=ko(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.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||Na(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 Gr(wo,Fa,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,l=null,u=null,c=!1,d=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},h=(y,I,V)=>{l&&l.abort(),l=sr(this.urlResolver.resolve(y,!1),I,V,()=>this._retryCallback()).withTimeout(Fa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(wo).withFinally(()=>{l=null}).send()},p=(y,I,V)=>{Yr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},S=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=W()-1e4,$=0;for(let D=0;D<this.bufferStates.length;D++){let E=this.bufferStates[D];y=Math.min(y,E.buf),E.ts<V&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${y} drop=${$} jitter=${this.sourceJitter}`);let A=y-gP;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?m(1.15):A>1?m(1.1):A>.3?m(1.05):m(1)}},v=y=>{let I,V=()=>I&&I.start?I.start.length:0,$=k=>I.start[k]/1e3,A=k=>I.dur[k]/1e3,D=k=>I.fragIndex+k,E=(k,O)=>({chunkIdx:D(k),startTS:$(k),dur:A(k),discontinuity:O}),x=()=>{let k=0;if(I&&I.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=O;this.sourceJitter>1&&(j+=this.sourceJitter-1);let se=I.dur.length-1;for(;se>=0&&(j-=I.dur[se],!(j<=0));--se);k=Math.min(se,I.dur.length-1-U),k=Math.max(k,0)}return E(k,!0)},R=k=>{let O=V();if(!(O<=0)){if(Na(k)){for(let U=0;U<O;U++)if($(U)>k)return E(U)}return x()}},q=k=>{let O=V(),U=k?k.chunkIdx+1:0,j=U-I.fragIndex;if(!(O<=0)){if(!k||j<0||j-O>bP)return t(`Resync: offset=${j} bChunks=${O} chunk=`+JSON.stringify(k)),x();if(!(j>=O))return E(U-I.fragIndex,!1)}},Q=(k,O,U)=>{u&&u.abort(),u=sr(this.urlResolver.resolve(k,!0,this.lowLatency),O,U,()=>this._retryCallback()).withTimeout(Fa).withRetryCount(wo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,O)=>{Q(y,U=>{if(!d())return;I=U;let j=!!I.lowLatency;j!==this.lowLatency&&S(j);let se=0;for(let et=0;et<I.dur.length;++et)se+=I.dur[et];se>0&&(Yr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(R(O))},()=>this._handleNetworkError())},nextChunk:q}},g=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),Yr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:I,logger:V}=this.params,$=v(e.jidxUrl),A,D,E,x,R=0,q,Q,Te,k=()=>{q&&(clearTimeout(q),q=void 0);let _=Math.max(vP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=R+_,oe=W(),Ie=Math.min(1e4,ne-oe);R=oe;let qe=()=>{u||d()&&$.seek(()=>{d()&&(R=W(),O(),k())})};Ie>0?q=window.setTimeout(()=>{this.paused?k():qe()},Ie):qe()},O=()=>{let _;for(;_=$.nextChunk(x);)x=_,gs(_);let ne=$.nextChunk(E);if(ne){if(E&&ne.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?k():(g(),this._initPlayerWith(e));return}et(ne)}else k()},U=(_,ne)=>{if(!d()||!this.sourceBuffer)return;let oe,Ie,qe,gr=ue=>{window.setTimeout(()=>{d()&&U(_,ne)},ue)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),gr(100);else{let ue=W(),tt=I.currentTime;!this.paused&&I.buffered.length>1&&Q===tt&&ue-Te>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),Q!==tt&&(Q=tt,Te=ue);let Ee=this._getBufferSizeSec();if(Ee>30)V(`Buffered ${Ee} seconds; delaying appendBuffer`),gr(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:ue,buf:Ee}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(De){if(De.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(oe=this.sourceBuffer.buffered.start(0),Ie=tt,Ie-oe>4&&this.sourceBuffer.remove(oe,Ie-3)),gr(1e3);else throw De}}},j=()=>{D&&A&&(V([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(E)]),U(D,function(){D=null,O()}))},se=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),et=_=>{d()&&p(se(_),(ne,oe)=>{if(d()){if(oe/=1e3,D=ne,E=_,n=_.startTS,oe){let Ie=Math.min(10,_.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}j()}},()=>this._handleNetworkError())},gs=_=>{d()&&(Yr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(_),!1)))},Ni=_=>{d()&&(e.cachedHeader=_,U(_,()=>{A=!0,j()}))};s=!0,$.seek(_=>{if(d()){if(R=W(),!_){k();return}x=_,!fP(y)||_.startTS>y?et(_):(E=_,O())}},y),e.cachedHeader?Ni(e.cachedHeader):h(e.headerUrl,Ni,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Na(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,Yr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Na(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(h,p)=>{let m=W();if(this.chunkRateEstimator.addInterval(h,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:b}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Po(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&u(),p},notifySwitch:d=>{let h=W();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Fa).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?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.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))},mP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as SP,filter as Vf,fromEvent as yP,interval as TP,isHigher as IP,isInvariantQuality as EP,isLower as xP,merge as PP,Subject as _f,Subscription as kP}from"@vkontakte/videoplayer-shared";var Ao=class{constructor(){this.onDroopedVideoFramesLimit$=new _f;this.subscription=new kP;this.playing=!1;this.tracks=[];this.forceChecker$=new _f;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!EP(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{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&&IP(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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(yP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=TP(this.droppedFramesChecker.checkTime).pipe(Vf(()=>this.playing),Vf(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(SP(this.droppedFramesChecker.checkTime)),r=PP(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){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>xP(r,a)?-1:1)?.[0]?.[0];return 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}},qa=Ao;import{map as wP,Observable as AP}from"@vkontakte/videoplayer-shared";import{fromEvent as RP}from"@vkontakte/videoplayer-shared";var Qr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var LP=(i,e)=>new AP(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||Qr()))},{...r,...e});a.observe(i);let s=RP(document,"visibilitychange").pipe(wP(n=>!document.hidden||Qr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),ve=LP;var NP=["paused","playing","ready"],FP=["paused","playing","ready"],zr=class{constructor(e){this.subscription=new BP;this.videoState=new L("stopped");this.representations$=new Lo([]);this.textTracksManager=new be;this.droppedFramesManager=new qa;this.maxSeekBackTime$=new Lo(1/0);this.zeroTime$=new Lo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:qf.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=ot(a.name)??_P(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ro(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(FP.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&NP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(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 l=a?.from;l&&l==="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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(K(this.params.source.url,l))}return;default:return Nf(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:qf.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Uf(this.videoState.stateChangeStarted$.pipe(Ua(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ua(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ee(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(Y(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=ie(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(Ua(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(MP(),Ua(a=>-a/1e3)).subscribe(this.params.output.duration$)).add($P({zeroTime:this.zeroTime$.pipe(DP(Ro)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(_e(this.video,this.params.desiredState.isLooped,t)).add(re(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(me(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(ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&VP(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{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":this.params.desiredState.playbackState.getTransition()?.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 Nf(a.to)}},t)).add(Uf(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,OP(["init"])).pipe(CP(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),te(this.video)}createLiveDashPlayer(){let e=new Wr({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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ro(t)?t:lt(e.map(({track:u})=>u),{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?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;Ff(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Ff(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(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Hf=zr;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)};import{assertNever as sw,assertNonNullable as tb,debounce as nw,ErrorCategory as Zo,filter as ow,filterChanged as rb,fromEvent as uw,isLowerOrEqual as ib,isNonNullable as lw,videoSizeToQuality as ab,map as eu,merge as ts,observableFrom as cw,observeElementSize as dw,once as pw,Subscription as hw,ValueSubject as sb}from"@vkontakte/videoplayer-shared";var Ha=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}},nr=class extends Ha{constructor(){super(),this.listeners||Ha.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)}},Kr=class{constructor(){Object.defineProperty(this,"signal",{value:new nr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?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>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Kr.prototype[Symbol.toStringTag]="AbortController",nr.prototype[Symbol.toStringTag]="AbortSignal");function ja(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 $o(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ja({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(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(u,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([h,n(l,u)])}return n(l,u)},Request:s}}var Jr=ja({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),jf=Jr?$o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=Jr?jf.fetch:window.fetch,yM=Jr?jf.Request:window.Request,ze=Jr?Kr:window.AbortController,TM=Jr?nr:window.AbortSignal;var Xm=Oe(Ta(),1);var Xr=(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};import{abortable as Ko,assertNonNullable as Ot,combine as Wm,ErrorCategory as pt,filter as Ka,filterChanged as Xk,fromEvent as hr,interval as Jo,isNonNullable as Qm,map as Xo,merge as fr,Subject as zm,Subscription as Km,tap as Zk,throttle as ew,ValueSubject as pe}from"@vkontakte/videoplayer-shared";var pr=Oe(Ba(),1);var qP=(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)},UP=i=>window.clearTimeout(i),Gf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Co=Gf?qP:window.requestIdleCallback,xM=Gf?UP:window.cancelIdleCallback;var _m=Oe(Da(),1);import{assertNever as HP,CurrentClientBrowser as jP,ErrorCategory as Yf,getCurrentBrowser as GP,Subject as Wf}from"@vkontakte/videoplayer-shared";var YP=16,Qf=!1;try{Qf=GP().browser===jP.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=YP}catch(i){console.error(i)}var Do=class{constructor(e){this.bufferFull$=new Wf;this.error$=new Wf;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yf.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){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()})}async abort(e){return new Promise(t=>{let r;Qf&&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(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yf.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){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:HP(t)}}},zf=Do;var Mo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as cr,assertNever as jk,assertNonNullable as Ke,ErrorCategory as dr,fromEvent as Go,getExponentialDelay as Yo,once as Gk,isNonNullable as Vm,isNullable as Je,Subject as Yk,Subscription as Wk,ValueSubject as yi}from"@vkontakte/videoplayer-shared";var B=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 or=class extends B{};var Zr=class extends B{};var ei=class extends B{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 ti=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ri=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends B{constructor(t,r){super(t,r);this.data=this.content}};var H=class extends B{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var At=class extends H{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,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ai=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends H{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 oi=class extends H{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ui=class extends H{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var li=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends H{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 di=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends H{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var fi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends H{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 bi=class extends H{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 gi=class extends H{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 QP={ftyp:ei,moov:ti,moof:ri,mdat:ii,sidx:At,trak:ai,mdia:li,mfhd:hi,tkhd:ci,traf:fi,tfhd:mi,tfdt:bi,trun:gi,minf:di,sv3d:si,st3d:ni,prhd:oi,proj:pi,equi:ui,uuid:Zr,unknown:or},Rt=class i{constructor(e={}){this.options={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{break}return t}createBox(e,t){let r=QP[e];return r?new r(t,new i):new or(t,new i)}};var ur=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 KP=new TextDecoder("ascii"),JP=i=>KP.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",XP=i=>{let e=new At(i,new Rt),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})},ZP=(i,e)=>{let r=new Rt().parse(i),a=new ur(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},ek=(i,e)=>{let r=new Rt().parse(i),s=new ur(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"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,h)=>d+h,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},tk=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 Rt().parse(i),a=new ur(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 l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},Kf={validateData:JP,parseInit:tk,getIndexRange:()=>{},parseSegments:XP,parseFeedableSegmentChunk:ZP,getSegmentEndTime:ek};import{assertNonNullable as Bo,isNonNullable as em,isNullable as ik}from"@vkontakte/videoplayer-shared";import{assertNever as rk}from"@vkontakte/videoplayer-shared";var Jf={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"}},Xf=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=vi(i,t),a=r in Jf,s=a?Jf[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 l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=vi(l),d=u*2**((o-1)*8)+c,h=t+o,p;return h+d>i.byteLength?p=new DataView(i.buffer,i.byteOffset+h):p=new DataView(i.buffer,i.byteOffset+h,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},vi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*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},Le=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return vi(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:rk(e)}},Lt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Xf(r);if(!e(a))return;a.type==="master"&&Lt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Zf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Xf(i);return Lt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Le(o,n):s===17026?t=Le(o,n):s===17029&&(r=Le(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var tm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ak=[231,22612,22743,167,171,163,160,175],sk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Lt(i,({tag:h,type:p,value:m,valueSize:S})=>{if(h===21419){let b=Le(m,p);u=vi(b)}else h!==21420&&(u=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+S):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Le(m,p):h===17545?a=Le(m,p):h===21420&&u===475249515?l=Le(m,p):h===374648427?Lt(m,({tag:b,type:v,value:g})=>b===30321?(c=Le(g,v)===1,!1):!0):s&&n&&tm.includes(h)&&(o=!0),!o}),Bo(e,"Failed to parse webm Segment start"),Bo(t,"Failed to parse webm Segment end"),Bo(a,"Failed to parse webm Segment duration"),r=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:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nk=i=>{if(ik(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ok=(i,e)=>{let t=!1,r=!1,a=o=>em(o.time)&&em(o.position),s=[],n;return Lt(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Le(u,l));break;case 183:break;case 241:n&&(n.position=Le(u,l));break;default:t&&tm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},uk=i=>{let e=0,t=!1;try{Lt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ak.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},rm={validateData:Zf,parseInit:sk,getIndexRange:nk,parseSegments:ok,parseFeedableSegmentChunk:uk};var qo=Oe(km(),1);import{isNonNullable as Am,isNullable as Rm}from"@vkontakte/videoplayer-shared";var wm=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Lm=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*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?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(i,e)=>{let t=i;t=(0,qo.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,qo.default)(t,n,(o,l)=>Rm(s)?o:Rm(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Cm=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,h,p=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)h=Lm(p);else if(m){let y=Lm(m);Am(y)&&(h=y)}else b&&(h=parseInt(b,10));let v=0,g=s.getAttribute("profiles")?.split(",")??[],w=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let y of l){let I=y.getAttribute("mimeType"),V=y.getAttribute("codecs"),$=y.getAttribute("contentType")??I?.split("/")[0],A=y.getAttribute("profiles")?.split(",")??[],D=y.querySelectorAll("Representation"),E=y.querySelector("SegmentTemplate");if($==="text"){for(let x of D){let R=x.getAttribute("id")||"",q=y.getAttribute("lang"),Q=y.getAttribute("label"),Te=x.querySelector("BaseURL")?.textContent?.trim()??"",k=new URL(Te||o,e).toString(),O=R.includes("_auto");a.text.push({id:R,lang:q,label:Q,isAuto:O,kind:"text",url:k})}continue}for(let x of D){let R=x.getAttribute("mimeType")??I,q=x.getAttribute("codecs")??V??"",Q=x.getAttribute("contentType")??R?.split("/")[0]??$,Te=y.getAttribute("profiles")?.split(",")??[],k=parseInt(x.getAttribute("width")??"",10),O=parseInt(x.getAttribute("height")??"",10),U=parseInt(x.getAttribute("bandwidth")??"",10)/1e3,j=x.getAttribute("frameRate")??"",se=x.getAttribute("quality")??void 0,et=j?wm(j):void 0,gs=x.getAttribute("id")??(v++).toString(10),Ni=Q==="video"?`${O}p`:Q==="audio"?`${U}Kbps`:q,_=`${gs}@${Ni}`,ne=x.querySelector("BaseURL")?.textContent?.trim()??"",oe=new URL(ne||o,e).toString(),Ie=[...g,...A,...Te],qe,gr=x.querySelector("SegmentBase"),ue=x.querySelector("SegmentTemplate")??E;if(gr){let Ee=x.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[De,vs]=Ee.split("-").map(Ft=>parseInt(Ft,10)),rt={from:De,to:vs},vr=x.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ss,Fi]=vr?vr.split("-").map(Ft=>parseInt(Ft,10)):[],Sr=vr?{from:Ss,to:Fi}:void 0;qe={type:"byteRange",url:oe,initRange:rt,indexRange:Sr}}else if(ue){let Ee={representationId:x.getAttribute("id")??void 0,bandwidth:x.getAttribute("bandwidth")??void 0},De=parseInt(ue.getAttribute("timescale")??"",10),vs=ue.getAttribute("initialization")??"",rt=ue.getAttribute("media"),vr=parseInt(ue.getAttribute("startNumber")??"",10)??1,Ss=$t(vs,Ee);if(!rt)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=ue.querySelectorAll("SegmentTimeline S")??[],Sr=[],Ft=0,ys="",Ts=0;if(Fi.length){let qi=vr,xe=0;for(let qt of Fi){let Me=parseInt(qt.getAttribute("d")??"",10),bt=parseInt(qt.getAttribute("r")??"",10)||0,Ui=parseInt(qt.getAttribute("t")??"",10);xe=Number.isFinite(Ui)?Ui:xe;let Is=Me/De*1e3,Xb=xe/De*1e3;for(let Hi=0;Hi<bt+1;Hi++){let Zb=$t(rt,{...Ee,segmentNumber:qi.toString(10),segmentTime:(xe+Hi*Me).toString(10)}),bu=(Xb??0)+Hi*Is,eg=bu+Is;qi++,Sr.push({time:{from:bu,to:eg},url:Zb})}xe+=(bt+1)*Me,Ft+=(bt+1)*Is}Ts=xe/De*1e3,ys=$t(rt,{...Ee,segmentNumber:qi.toString(10),segmentTime:xe.toString(10)})}else if(Am(h)){let xe=parseInt(ue.getAttribute("duration")??"",10)/De*1e3,qt=Math.ceil(h/xe),Me=0;for(let bt=1;bt<qt;bt++){let Ui=$t(rt,{...Ee,segmentNumber:bt.toString(10),segmentTime:Me.toString(10)});Sr.push({time:{from:Me,to:Me+xe},url:Ui}),Me+=xe}Ts=Me,ys=$t(rt,{...Ee,segmentNumber:qt.toString(10),segmentTime:Me.toString(10)})}let Jb={time:{from:Ts,to:1/0},url:ys};qe={type:"template",baseUrl:oe,segmentTemplateUrl:rt,initUrl:Ss,totalSegmentsDurationMs:Ft,segments:Sr,nextSegmentBeyondManifest:Jb,timescale:De}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!R)continue;let tt={video:"video",audio:"audio",text:"text"}[Q];tt&&a[tt].push({id:_,kind:tt,segmentReference:qe,profiles:Ie,duration:h,bitrate:U,mime:R,codecs:q,width:k,height:O,fps:et,quality:se})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:h,container:w,representations:a}};var Ho=Oe(Ba(),1);import{videoSizeToQuality as Hk}from"@vkontakte/videoplayer-shared";var Dm=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ot(s):void 0)??Hk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Mm=({id:i,bitrate:e})=>({id:i,bitrate:e}),Om=(i,e,t)=>{let r=e.indexOf(t);return(0,Ho.default)(i,Math.round(i.length*r/e.length))??(0,Ho.default)(i,-1)},Bm=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),jo=i=>"url"in i,Ct=i=>i.type==="template",Si=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ti=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new yi(0);this.onLastSegment$=new yi(!1);this.fullyBuffered$=new yi(!1);this.playingRepresentation$=new yi(void 0);this.playingRepresentationInit$=new yi(void 0);this.error$=new Yk;this.gaps=[];this.subscription=new Wk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ze;this.destroyAbortController=new ze;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=cr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zf(this.sourceBuffer),this.subscription.add(Go(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:dr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(Go(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:dr.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,Mo(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);Ke(r,"No init buffer for starting representation"),Ke(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=cr(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);Ke(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Je(a)||Je(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Ke(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();Vm(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=cr(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let l=e.find(d=>d.id===o);l&&this.representations.set(o,l);let u=this.representations.get(o);if(!u||!Ct(u.segmentReference))return;let c=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,c)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(t);Ke(r);let a=this.segments.get(t);Ke(a,"No segments for starting representation");let s=this.initData.get(t);if(Ke(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=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!c?.dynamic,this.container=r,r){case"mp4":this.containerParser=Kf;break;case"webm":this.containerParser=rm;break;default:jk(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 ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Je(e)||Je(this.downloadingRepresentationId)||Je(this.playingRepresentationId)||Je(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ke(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ct(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Mo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ct(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let c=(0,pr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,pr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}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;Vm(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?.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){for(let t of e?.representations[this.kind].values()??[]){if(!t||!Ct(t.segmentReference))return;let r=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),a=this.segments.get(t.id)??[],s=(0,pr.default)(a,-1)?.time.to??0,n=r?.findIndex(o=>Math.floor(s)>=Math.floor(o.time.from)&&Math.floor(s)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=r.slice(n+1);this.segments.set(t.id,[...a,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!Ct(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=$t(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}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:h,to:p}},m)=>{let S=h<=r&&p>=r,b=h>r||S||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&h<=r+v||p<=r+v;return(d==="none"||d==="partially_ejected"&&b&&g&&this.sourceBuffer&&!Xr(this.sourceBuffer.buffered,r))&&b&&g});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await cr(o,async function*(){let c=Yo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let h=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,h)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Si(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,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&&(await cr(n,async function*(){let l=Yo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),Go(window,"online").pipe(Gk()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Si(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ct(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,pr.default)(e,0).byte.from,to:(0,pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ct(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=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.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 l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,h=l==="byteRange",p=h?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!h||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let S=h?d.byte.from-r:0,b=h?d.byte.to-r:e.byteLength,v=S<a,g=b<=a;if(d.status==="downloading"&&v&&g){d.status="downloaded";let w=new DataView(e.buffer,e.byteOffset+S,p);this.sourceBufferTaskQueue.append(w,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(c.loadedBytes=Math.min(p,a-S),c.loadedBytes>c.feedingBytes)){let w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===p?w:this.containerParser.parseFeedableSegmentChunk(w);y?.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=y.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",jo(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.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||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Co(()=>(0,_m.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?cr(this.destroyAbortController.signal,async function*(){let o=Yo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Ct(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:dr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Je(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=jo(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let h of this.segments.values())for(let p of h)if(p.status==="none"&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.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 u=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+u&&d.status==="fed"&&l(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=Co(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:dr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Je(this.sourceBuffer)||Je(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),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.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 Ii=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Nm=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Ei,assertNever as Fm,fromEvent as qm,merge as Qk,now as Wo,Subscription as zk,ValueSubject as Qo}from"@vkontakte/videoplayer-shared";var Ga=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Qo(void 0);this.lastConnectionReused$=new Qo(void 0);this.lastRequestFirstBytes$=new Qo(void 0);this.abortAllController=new ze;this.subscription=new zk;this.fetchManifest=Ei(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ii(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(xi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Ei(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let A=new URL(u,location.href);A.searchParams.append("bytes",`${r.from}-${r.to}`),u=A.toString();break}default:Fm(t)}this.requestQuic&&(u=Ii(u));let d=this.abortAllController.signal,h;if(n){let A=new ze;if(h=Qk(qm(this.abortAllController.signal,"abort"),qm(n,"abort")).subscribe(()=>{try{A.abort()}catch(D){xi(D)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(D){xi(D)}d=A.signal}let p=Wo(),m=yield Qe(u,{priority:s,headers:c,signal:d}).catch(xi),S=Wo();if(!m)return h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-p),!m.ok||!m.body)return h?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!o)return h?.unsubscribe(),m.arrayBuffer();let[b,v]=m.body.tee(),g=b.getReader();o&&this.throughputEstimator?.trackStream(v,l);let w=0,y=new Uint8Array(0),I=!1,V=A=>{h?.unsubscribe(),I=!0,xi(A)},$=Ei(d,async function*({done:A,value:D}){if(w===0&&this.lastRequestFirstBytes$.next(Wo()-p),d.aborted){h?.unsubscribe();return}if(!A&&D){let E=new Uint8Array(y.length+D.length);E.set(y),E.set(D,y.length),y=E,w+=D.byteLength,a?.(new DataView(y.buffer),w),yield g?.read().then($,V)}}.bind(this));return yield g?.read().then($,V),h?.unsubscribe(),I?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=Ei(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,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 h=new DataView(d,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let S;if(l)S=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;S=new DataView(v)}let b=t.parseSegments(S,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ei(this.abortAllController.signal,async function*(e,t){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=>({...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}=Nm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Fm(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},xi=i=>{if(!Si(i))throw i};var Dt=(i,e,t)=>t*e+(1-t)*i,zo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Um=(i,e,t,r)=>{let a=0,s=t,n=zo(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Kk,ValueSubject as Hm}from"@vkontakte/videoplayer-shared";var dt=class{constructor(e){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 Hm(e.initial),this.debounced$=new Hm(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new J(`raw_${t}`),this.smoothedSeries$=new J(`smoothed_${t}`),this.reportedSeries$=new J(`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+=(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)&&(Kk(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 Ya=class extends dt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Dt(this.slow,t,this.params.emaAlphaSlow),this.fast=Dt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var Wa=class extends dt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=zo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,t,this.params.emaAlpha);let a=Um(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Qa=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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ya({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Wa({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 Qa({initial:e,label:"liveEdgeDelay",...t})}};var jm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Xe=()=>window.ManagedMediaSource||window.MediaSource,za=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Gm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Ym=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Jm=["timeupdate","progress","play","seeked","stalled","waiting"];var Ja=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Km;this.representationSubscription=new Km;this.state$=new L("none");this.currentVideoRepresentation$=new pe(void 0);this.currentVideoRepresentationInit$=new pe(void 0);this.currentVideoSegmentLength$=new pe(0);this.currentAudioSegmentLength$=new pe(0);this.error$=new zm;this.lastConnectionType$=new pe(void 0);this.lastConnectionReused$=new pe(void 0);this.lastRequestFirstBytes$=new pe(void 0);this.isLive$=new pe(!1);this.liveDuration$=new pe(0);this.liveAvailabilityStartTime$=new pe(void 0);this.bufferLength$=new pe(0);this.liveLoadBufferLength$=new pe(0);this.livePositionFromPlayer$=new pe(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new zm;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=Ko(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ko(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=Cm(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let r=({kind:a,mime:s,codecs:n})=>!!(this.element?.canPlayType?.(s)&&Xe()?.isTypeSupported?.(`${s}; codecs="${n}"`)||a==="text");return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:(0,Xm.default)(Object.entries(t.representations).map(([a,s])=>[a,s.filter(r)]))}}.bind(this));this.initRepresentations=Ko(this.destroyController.signal,async function*(e,t,r){Ot(this.manifest),Ot(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(hr(p,"error").pipe(Ka(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ym():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&za())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}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 Ti("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Qm(t)&&(this.audioBufferManager=new Ti("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(Jo(1e3).subscribe(p=>{if(this.element?.paused){let m=ho(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(fr(...Jm.filter(p=>p!=="waiting").map(p=>hr(this.element,p))).pipe(Xo(p=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),Xk(),Ka(p=>!!p),Zk(p=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(Ka(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,g=m-S,w=1+Math.sign(g)*v;Math.abs(g)<b?w=1:Math.abs(g)>b*2&&(w=1+Math.sign(g)*v*2),jm(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let S=0;if(m){let b=(this.element?.currentTime??0)*1e3;S=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==S&&this.liveLoadBufferLength$.next(S)}));let p=0;this.representationSubscription.add(Wm({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ew(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:S})=>{if(Ot(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,v=ho(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,V=this.isActiveLowLatency?S:m,$=3;if(this.isActiveLowLatency?$=0:V<w+I&&V>=w?$=1:v!==0&&V<w&&($=2),isFinite(m)&&(p=m>p?m:p),$===2||$===1){let A=p-(w+y),D=this.normolizeLiveOffset(Math.trunc(v+A/b)),E=Math.abs(D-v),x;!m||E<=this.tuning.dashCmafLive.offsetCalculationError?x=v:D>0&&E>this.tuning.dashCmafLive.offsetCalculationError?x=D:x=0,this.manifestUrlString=K(this.manifestUrlString,x,2)}$!==3&&$!==0&&(p=0,this.updateLive())}))}let o=fr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Xo(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=fr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Xo(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(fr(this.forceEnded$,Wm({allBuffersFull:o,someBufferEnded:l}).pipe(Ka(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(fr(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));let u=this.manifest.duration??0,c=(p,m)=>Math.max(p,m.duration??0),d=this.manifest.representations.audio.reduce(c,u),h=this.manifest.representations.video.reduce(c,u);(d||h)&&(this.source.duration=Math.max(d,h)/1e3),this.audioBufferManager&&Qm(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Jo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ga({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Mt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){Ot(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){Ot(this.element),this.state$.setState("running"),this.subscription.add(fr(...Jm.map(e=>hr(this.element,e)),hr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(hr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(hr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Xr(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)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Jo(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:pt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){Ot(this.element),Ot(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Xr(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.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 Xa=class{constructor(e,t){this.fov=e,this.orientation=t}};var Za=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/(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??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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={...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*(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 Zm=`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 eb=`#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 Lr{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,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 kr(this.params.fov,this.params.orientation),this.cameraRotationManager=new $r(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),r=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,-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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(wr,this.gl.VERTEX_SHADER),i=this.createShader(Pr,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,r=e-i,n=t-s,o=e+i,d=t-s,c=e+i,u=t+s,h=e-i,p=t+s;return[r,n,o,d,c,u,h,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(){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 Es{scene3D;subscription=new ee;videoState=new ne(se.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new it;droppedFramesManager=new us;videoTracks$=new g([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new oa;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=lt(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(qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ar({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=mt(this.video),s=this.constructor.name,r=o=>{e.error$.next({id:s,category:P.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:(o,d)=>this.subscription.add(o.subscribe(d,r))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:r}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(T(c=>c.map(({track:u})=>u)))}),r(i.ended$,e.endedEvent$),r(i.looped$,e.loopedEvent$),r(i.error$,e.error$),r(i.isBuffering$,e.isBuffering$),r(i.currentBuffer$,e.currentBuffer$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.isLive$,e.isLive$),r(this.player.lastRequestFirstBytes$.pipe(oe(A),Se()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ht(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,i.playbackRateState$,s)),r(Ms(this.video),this.elementSize$),r(Dt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),R(t.playbackState,l.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),R(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Le.MANIFEST_READY){const u=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();v(h,"Manifest not loaded or empty");const p=Array.from(h.audio).sort((y,k)=>k.bitrate-y.bitrate),f=Array.from(h.video).sort((y,k)=>k.bitrate-y.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const y of p){const k=hr(y);k&&this.audioTracks.push({track:k,representation:y})}for(const y of f){const k=ur(y);if(k){u.push({track:k,representation:y});const _=!this.params.tuning.isAudioDisabled&&lr(p,f,y);_&&this.audioRepresentations.set(y.id,_)}}this.videoTracks$.next(u);for(const y of S){const k=fr(y);k&&this.textTracks.push({track:k,representation:y})}this.params.output.availableVideoTracks$.next(u.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));const w=this.selectVideoRepresentation();v(w),this.player.initRepresentations(w.id,this.audioRepresentations.get(w.id)?.id,this.params.sourceHls)}else c===Le.REPRESENTATIOS_READY&&(this.videoState.setState(se.READY),this.player.initBuffer())},s));const n=c=>e.error$.next({id:"RepresentationSwitch",category:P.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(O(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$,C(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),u=this.player.state$.getTransition();if(c!==Le.RUNNING||u||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),S=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let w=h.id;!this.params.output.elementVisible$.getValue()&&f&&(w=this.videoTracks$.getValue().map(k=>k.representation).sort((k,_)=>_.bitrate-k.bitrate).filter(k=>{const _=dt(k),M=dt(h);if(_&&M)return ei(_,M)&&ei(_,S)}).map(k=>k.id)[0]),this.player.switchRepresentation(me.VIDEO,w).catch(n);const y=this.audioRepresentations.get(h.id);y&&this.player.switchRepresentation(me.AUDIO,y.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(de(),T(c=>c&&this.videoTracks$.getValue().find(({representation:{id:u}})=>u===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(u){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${u}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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 o=t.playbackState.stateChangeStarted$.pipe(T(({to:c})=>c===l.READY),de());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===l.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const d=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:h}})=>h===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),r=_t(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(r/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=oi(this.videoTracks$.getValue().map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),u=e?c??i:i??c;return u&&this.videoTracks$.getValue().find(({track:h})=>h===u)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===G.Requested&&i?.to!==l.PAUSED&&e!==se.STOPPED&&t!==l.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===l.STOPPED){e!==se.STOPPED&&(this.videoState.startTransitionTo(se.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(se.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}switch(e){case se.STOPPED:this.videoState.startTransitionTo(se.READY),this.prepare();return;case se.READY:t===l.PAUSED?(this.videoState.setState(se.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):i?.to===l.READY&&R(this.params.desiredState.playbackState,l.READY);return;case se.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case se.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(se.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()):i?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;default:return V(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Lr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){gt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(se.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.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),ft(this.video)}}class Dr extends Es{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class xr extends Es{constructor(e){super(e),this.liveOffset=new xi}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(De({interval:Mt(Et),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===se.PLAYING&&!this.player.isActiveLowLatency){const r=e.position$.getValue()+(s-1);e.position$.next(r),this.liveOffset?.resetTo(-r*1e3)}})).add(De({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(T(({liveBufferTime:s,liveAvailabilityStartTime:r})=>s&&r?s+r:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===se.PAUSED,r=-e,n=Math.trunc(r/1e3<=Math.abs(this.params.output.duration$.getValue())?r:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const _e={};var z;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const Tt=(a,e)=>new Li(t=>{const i=(s,r)=>t.next(r);return a.on(e,i),()=>a.off(e,i)});class Cr{subscription=new ee;videoState=new ne(z.INITIALIZING);video;params;hls;textTracksManager=new it;trackLevels=new Map;constructor(e){this.video=lt(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(qe(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ft(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:P.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(_e.Hls=s.default,_e.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){v(_e.Hls,"hls.js not loaded"),this.hls=new _e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){v(_e.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:P.WTF,message:"HlsJsProvider internal logic error",thrown:c})},s=mt(this.video),r=(c,u)=>this.subscription.add(c.subscribe(u,i));r(s.timeUpdate$,t.position$),r(s.durationChange$,t.duration$),r(s.ended$,t.endedEvent$),r(s.looped$,t.loopedEvent$),r(s.error$,t.error$),r(s.isBuffering$,t.isBuffering$),r(s.currentBuffer$,t.currentBuffer$),r(s.loadStart$,t.firstBytesEvent$),r(s.playing$,t.firstFrameEvent$),r(s.canplay$,t.canplay$),r(s.seeked$,t.seekedEvent$),r(s.inPiP$,t.inPiP$),r(s.inFullscreen$,t.inFullscreen$),this.subscription.add(Ht(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lt(this.video,e.playbackRate,s.playbackRateState$,i)),r(Dt(this.video),t.elementVisible$),this.subscription.add(Tt(this.hls,_e.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:P.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),R(e.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),R(e.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i)),r(Tt(this.hls,_e.Events.MANIFEST_PARSED).pipe(T(({levels:c})=>c.reduce((u,h)=>{const p=h.name||h.height.toString(10),{width:f,height:S}=h,w=ni(h.attrs.QUALITY??"")??dt({width:f,height:S});if(!w)return u;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,k={id:p.toString(),quality:w,bitrate:h.bitrate/1e3,size:{width:f,height:S},fps:y};return this.trackLevels.set(p,{track:k,level:h}),u.push(k),u},[]))),t.availableVideoTracks$),r(Tt(this.hls,_e.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){const u=[];for(const h of c.subtitleTracks){const p=h.name,f=h.attrs.URI||"",S=h.lang,w="internal";u.push({id:p,url:f,language:S,type:w})}e.internalTextTracks.startTransitionTo(u)}}),r(Tt(this.hls,_e.Events.LEVEL_LOADING).pipe(T(({url:c})=>qe(c))),t.hostname$),r(Tt(this.hls,_e.Events.FRAG_CHANGED),c=>{const{video:u,audio:h}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((u?.endPTS??0)-(u?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((h?.endPTS??0)-(h?.startPTS??0))*1e3)}),this.subscription.add(Qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));const n=c=>Array.from(this.trackLevels.values()).find(({level:u})=>u===c)?.track,o=Tt(this.hls,_e.Events.LEVEL_SWITCHED).pipe(T(({level:c})=>n(this.hls.levels[c])));o.pipe(oe(A)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Qe(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{if(Q(c))return;const u=this.trackLevels.get(c.id)?.level;if(!u)return;const h=this.hls.levels.indexOf(u),p=this.hls.currentLevel,f=this.hls.levels[p];!f||u.bitrate>f.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:i})),r(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==z.INITIALIZING)switch(i?.to!==l.PAUSED&&s.state===G.Requested&&this.seek(s.position),t){case l.STOPPED:switch(e){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:V(e)}break;case l.READY:switch(e){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:V(e)}break;case l.PLAYING:switch(e){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:V(e)}break;case l.PAUSED:switch(e){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED);break;case z.PLAYING:this.pause();break;default:V(e)}break;default:V(t)}};prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(z.PLAYING),await gt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:t}))||(this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(z.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(z.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0)}}const ji="X-Playback-Duration";var Ji=async a=>{const e=await Vt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(ji)?parseInt(e.headers.get(ji),10):void 0};const Rr=a=>{let e=null;if(a.QUALITY&&(e=ni(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=dt({width:t,height:i})}return e??null},Ir=(a,e)=>{const t=a.split(`
46
- `),i=[],s=[];for(let r=0;r<t.length;r++){const n=t[r],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),d=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!d)){if(o){const c=Object.fromEntries(o[1].split(",").map(y=>y.split("="))),u=c.QUALITY??`stream-${c.BANDWIDTH}`,h=Rr(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const f=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let S;if(c.RESOLUTION){const[y,k]=c.RESOLUTION.split("x").map(_=>parseInt(_,10));y&&k&&(S={width:y,height:k})}const w=new URL(t[++r],e).toString();h&&i.push({id:u,quality:h,url:w,bandwidth:p,size:S,fps:f})}if(d){const c=Object.fromEntries(d[1].split(",").map(f=>f.split("=")).map(([f,S])=>[f,S.replace(/^"|"$/g,"")])),u=c.URI?.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,p=c.NAME;u&&h&&s.push({type:"internal",id:h,label:p,language:h,url:u,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:s}},Br=a=>new Promise(e=>{setTimeout(()=>{e()},a)});let Si=0;const Bi=async(a,e=a,t)=>{const s=await(await Vt(a)).text();Si+=1;try{const{qualityManifests:r,textTracks:n}=Ir(s,e);return{qualityManifests:r,textTracks:n}}catch{if(Si<=t.manifestRetryMaxCount)return await Br(Xt(Si-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Bi(a,e,t)}return{qualityManifests:[],textTracks:[]}};var K;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(K||(K={}));class Mr{subscription=new ee;videoState=new ne(K.STOPPED);video;params;textTracksManager=new it;masterManifest;manifests$=new g([]);maxSeekBackTime$;liveOffset=new xi;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$e.INVARIANT,url:this.params.source.url},Bi(Oe(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:P.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:P.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(qe(this.params.source.url)),this.maxSeekBackTime$=new g(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:P.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=mt(this.video),r=(o,d)=>this.subscription.add(o.subscribe(d,i));r(s.ended$,e.endedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,i)),r(Dt(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),R(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),R(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(de(),T(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&A(c.to)){const h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(qe(p.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),d&&d.from===K.CHANGING_MANIFEST&&this.videoState.setState(d.to),o&&o.state===G.Requested&&this.seek(o.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(De({startTime:this.manifestStartTime$.pipe(oe(A)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),i)),this.subscription.add(this.manifests$.pipe(T(o=>o.map(({id:d,quality:c,size:u,bandwidth:h,fps:p})=>({id:d,quality:c,size:u,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ft(this.video)}prepare(){const e=this.selectManifest();if(Q(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:o,min:d}=t?.to??i??{};for(const[c,u]of[[o,"mq"],[d,"lq"]]){const h=String(parseFloat(c||""));u&&c&&s.searchParams.set(u,h)}}const r=this.params.format===m.HLS_LIVE_CMAF?le.DASH_CMAF_OFFSET_P:le.OFFSET_P,n=Oe(s.toString(),this.liveOffset.getTotalOffset(),r);this.video.setAttribute("src",n),this.video.load(),Ji(n).then(o=>{if(!Q(o))this.maxSeekBackTime$.next(o);else{const d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Q(d)||!isFinite(d))try{Vt(n).then(c=>c.text()).then(c=>{const u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(u){const h=new URL(u,n).toString();Ji(h).then(p=>{Q(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===l.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.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(K.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(r||n||o){const u=this.videoState.getState();this.videoState.setState(K.CHANGING_MANIFEST),this.videoState.startTransitionTo(u),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state===G.None&&this.params.desiredState.seekState.setState({state:G.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&c.state===G.Requested){this.videoState.startTransitionTo(K.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case K.READY:i===l.READY?R(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(K.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case K.PAUSED:if(i===l.PLAYING)if(this.videoState.startTransitionTo(K.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 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.prepare()}else s?.to===l.PAUSED&&(R(this.params.desiredState.playbackState,l.PAUSED),this.liveOffset.pause());return;case K.CHANGING_MANIFEST:break;default:return V(t)}}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(te||(te={}));class _r{subscription=new ee;videoState=new ne(te.STOPPED);video;params;textTracksManager=new it;masterManifest;manifests$=new g([]);constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$e.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(qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Bi(Oe(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:P.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:P.WTF,message:"HlsProvider internal logic error",thrown:o})},s=mt(this.video),r=(o,d)=>this.subscription.add(o.subscribe(d));if(r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ht(this.video,t.isLooped,i)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),R(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),R(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&A(c.to)){const h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(qe(p.url));const f=this.params.desiredState.playbackRate.getState(),S=this.params.output.element$.getValue()?.playbackRate;if(f!==S){const w=this.params.output.element$.getValue();w&&(this.params.desiredState.playbackRate.setState(f),w.playbackRate=f)}}}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),d&&d.from===te.CHANGING_MANIFEST&&this.videoState.setState(d.to),o.state===G.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(T(o=>o.map(({id:d,quality:c,size:u,bandwidth:h,fps:p})=>({id:d,quality:c,size:u,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!_s()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(O(C(o,"addtrack"),C(o,"removetrack"),C(o,"change"),Ce(["init"])).subscribe(()=>{for(let d=0;d<o.length;d++)o[d].mode="hidden"},i))}const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ft(this.video)}prepare(){const e=this.selectManifest();if(Q(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:r,min:n}=t?.to??i??{};for(const[o,d]of[[r,"mq"],[n,"lq"]]){const c=String(parseFloat(o||""));d&&o&&s.searchParams.set(d,c)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===l.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(r||n||o){const u=this.videoState.getState();this.videoState.setState(te.CHANGING_MANIFEST),this.videoState.startTransitionTo(u);const{currentTime:h}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state===G.None&&this.params.desiredState.seekState.setState({state:G.Requested,position:h*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&c.state===G.Requested&&this.seek(c.position),t){case te.READY:i===l.READY?R(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(te.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):s?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case te.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;case te.CHANGING_MANIFEST:break;default:return V(t)}}}var re;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(re||(re={}));class Or{subscription=new ee;videoState=new ne(re.STOPPED);video;trackUrls={};params;textTracksManager=new it;constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const r=s.toString(10);this.trackUrls[r]={track:{quality:t,id:r},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:P.WTF,message:"MpegProvider internal logic error",thrown:o})},s=mt(this.video),r=(o,d)=>this.subscription.add(o.subscribe(d,i));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Ht(this.video,t.isLooped,i)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,i)),r(Dt(this.video),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),R(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),R(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===re.READY&&this.videoState.setState(re.READY);const o=this.params.desiredState.videoTrack.getTransition();if(o&&A(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);const d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){const u=this.params.output.element$.getValue();u&&(this.params.desiredState.playbackRate.setState(d),u.playbackRate=d)}}this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ft(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;v(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];v(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=$i(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(qe(t))}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(r&&e!==re.READY&&!n){this.handleQualityLimitTransition(r.to.max);return}if(e===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){const{currentTime:d}=this.video;this.prepare(),o.state===G.None&&this.params.desiredState.seekState.setState({state:G.Requested,position:d*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==l.PAUSED&&o.state===G.Requested&&this.seek(o.position),e){case re.READY:t===l.READY?R(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):i?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case re.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;default:return V(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(o=>!ut(o.track.quality)&&ei(o.track.quality,e))?.track,r=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[r??"0"]?.track;if(s&&n&&yi(n.quality,s.quality)&&(t=s),!t){const o=Object.values(this.trackUrls).filter(c=>!ut(c.track.quality)&&kt(c.track.quality,e)),d=o.length;d&&(t=o[d-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(r=>r.track);t=oi(s,{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:i})}}const Xi=["stun:videostun.mycdn.me:80"],Nr=1e3,Fr=3,bi=()=>null;class Vr{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=bi;externalStopCallback=bi;externalErrorCallback=bi;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Xi}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:P.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),Nr)}normalizeOptions(e={}){const t={stunServerList:Xi,maxRetryNumber:Fr,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Z;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Z||(Z={}));class Ur{subscription;params;log;video;videoState=new ne(Z.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new ee,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=lt(e.container),this.liveStreamClient=new Vr(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),ft(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:P.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(T(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(T(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=mt(this.video),r=(n,o)=>this.subscription.add(n.subscribe(o,i));r(s.timeUpdate$,e.liveTime$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(Dt(this.video),this.params.output.elementVisible$),this.subscription.add(s.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(pt(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case Z.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(l.STOPPED);break;case Z.READY:break;case Z.PAUSED:t.playbackState.setState(l.PAUSED);break;case Z.PLAYING:t.playbackState.setState(l.PLAYING);break;default:return V(n.to)}},i)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(qe(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:$e.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,l.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Z.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:P.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.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(Z.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(r){this.prepare();return}switch(e){case Z.READY:t===l.PAUSED?(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):i?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case Z.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;default:return V(e)}}}class Ki{iterator;current;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 ye;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg",a.DASH_ANY_MPEG="dash_any_mpeg",a.DASH_ANY_WEBM="dash_any_webm",a.DASH_SEP="dash_sep"})(ye||(ye={}));var tt;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(tt||(tt={}));const As=Pi().device===Os.Android,ri=document.createElement("video"),Hr='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Yr='video/mp4; codecs="hev1.1.6.L93.B0"',ks='video/webm; codecs="vp09.00.10.08"',$s='video/webm; codecs="av01.0.00M.08"',Gr='audio/mp4; codecs="mp4a.40.2"',qr='audio/webm; codecs="opus"',rt={mms:vs(),mse:vr(),hls:!!(ri.canPlayType?.("application/x-mpegurl")||ri.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!ri.canPlayType?.("video/mp4"),webm:!!ri.canPlayType?.("video/webm"),cmaf:!0},Ye={h264:!!at()?.isTypeSupported?.(Hr),h265:!!at()?.isTypeSupported?.(Yr),vp9:!!at()?.isTypeSupported?.(ks),av1:!!at()?.isTypeSupported?.($s),aac:!!at()?.isTypeSupported?.(Gr),opus:!!at()?.isTypeSupported?.(qr)},Bt=(Ye.h264||Ye.h265)&&Ye.aac;let nt;const zr=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:$s}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:ks}})]);nt={[m.DASH_WEBM_AV1]:e,[m.DASH_WEBM]:t}};try{zr()}catch(a){console.error(a)}const Ut=rt.hls&&Pe.mp4,Wr=()=>Object.keys(Ye).filter(a=>Ye[a]),Qr=(a,e=!1,t=!1)=>{const i=rt.mse||rt.mms&&t;return a.filter(s=>{switch(s){case m.DASH_SEP:return i&&Pe.mp4&&Bt;case m.DASH_WEBM:return i&&Pe.webm&&Ye.vp9&&Ye.opus;case m.DASH_WEBM_AV1:return i&&Pe.webm&&Ye.av1&&Ye.opus;case m.DASH_LIVE:return rt.mse&&Pe.mp4&&Bt;case m.DASH_LIVE_CMAF:return i&&Pe.mp4&&Bt&&Pe.cmaf;case m.DASH_ONDEMAND:return i&&Pe.mp4&&Bt;case m.HLS:case m.HLS_ONDEMAND:return Ut||e&&rt.mse&&Pe.mp4&&Bt;case m.HLS_LIVE:case m.HLS_LIVE_CMAF:return Ut;case m.MPEG:return Pe.mp4;case m.DASH_LIVE_WEBM:return!1;case m.WEB_RTC_LIVE:return rt.webrtc&&rt.ws&&Ye.h264&&(Pe.mp4||Pe.webm);default:return V(s)}})},et=a=>{const e=m.DASH_WEBM,t=m.DASH_WEBM_AV1;switch(a){case tt.VP9:return[e,t];case tt.AV1:return[t,e];case tt.NONE:return[];case tt.SMOOTH:return nt?nt[t].smooth?[t,e]:nt[e].smooth?[e,t]:[t,e]:[e,t];case tt.POWER_EFFICIENT:return nt?nt[t].powerEfficient?[t,e]:nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:V(a)}return[e,t]},jr=({webmCodec:a,androidPreferredFormat:e})=>{if(As)switch(e){case ye.MPEG:return[m.MPEG,...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND];case ye.HLS:return[m.HLS,m.HLS_ONDEMAND,...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.MPEG];case ye.DASH:return[...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG];case ye.DASH_ANY_MPEG:return[m.DASH_SEP,m.DASH_ONDEMAND,m.MPEG,...et(a),m.HLS,m.HLS_ONDEMAND];case ye.DASH_ANY_WEBM:return[...et(a),m.MPEG,m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND];case ye.DASH_SEP:return[m.DASH_SEP,m.MPEG,...et(a),m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND];default:V(e)}return Ut?[...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG]:[...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG]},Jr=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{const i=e?[m.DASH_LIVE_CMAF,m.DASH_LIVE]:[m.DASH_LIVE,m.DASH_LIVE_CMAF],s=e?[m.HLS_LIVE_CMAF,m.HLS_LIVE]:[m.HLS_LIVE,m.HLS_LIVE_CMAF],r=[...i,...s],n=[...s,...i];let o;if(As)switch(a){case ye.DASH:case ye.DASH_ANY_MPEG:case ye.DASH_ANY_WEBM:case ye.DASH_SEP:{o=r;break}case ye.HLS:case ye.MPEG:{o=n;break}default:V(a)}else Ut?o=n:o=r;return t?[m.WEB_RTC_LIVE,...o]:[...o,m.WEB_RTC_LIVE]},Zi=a=>a?[m.HLS_LIVE,m.HLS_LIVE_CMAF,m.DASH_LIVE_CMAF]:[m.DASH_WEBM,m.DASH_WEBM_AV1,m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG];var Xr=a=>new Li(e=>{const t=new ee,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(T(({from:c,to:u})=>`${c}-${u}`)),s=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$.pipe(T(({type:c})=>c!==void 0)),n=new x;let o=0,d="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),d=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),d="unknown",o=0})),t.add(r.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Kr={chunkDuration:5e3,maxParallelRequests:5};class Zr{current$=new g({type:void 0});providerError$=new x;noAvailableProvidersError$=new x;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),currentVideoSegmentLength$:new g(0),currentAudioSegmentLength$:new g(0),availableVideoTracks$:new g([]),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),autoVideoTrackLimitingAvailable$:new g(!1),autoVideoTrackLimits$:new g(void 0),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new g(void 0),isLowLatency$:new g(!1),canChangePlaybackSpeed$:new g(!0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),inPiP$:new g(!1),inFullscreen$:new g(!1),element$:new g(void 0),elementVisible$:new g(!0),availableSources$:new g(void 0),is3DVideo$:new g(!1)};subscription=new ee;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Qr([...Jr(this.params.tuning),...jr(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>A(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let r=[];i?r=[i]:s.length?r=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:r=t,this.log({message:`Selected formats: ${r.join(" > ")}`}),this.screenFormatsIterator=new Ki(r);const n=[...Zi(!0),...Zi(!1)];this.chromecastFormatsIterator=new Ki(n.filter(o=>A(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(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(Q(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:P.WTF,message:"Failed to create provider",thrown:s})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),s=i.state!==G.None;if(this.params.desiredState.seekState.setState({state:G.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ge.SCREEN:return this.createScreenProvider(t);case ge.CHROMECAST:return this.createChromecastProvider(t);default:return V(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,r=this.providerOutput,n={container:i,source:null,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case m.DASH_SEP:case m.DASH_WEBM:case m.DASH_WEBM_AV1:case m.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t[m.HLS_ONDEMAND]||t[m.HLS]);return v(o),new Dr({...n,source:o,sourceHls:d})}case m.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return v(o),new xr({...n,source:o})}case m.HLS:case m.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return v(o),Ut||!this.params.tuning.useHlsJs?new _r({...n,source:o}):new Cr({...n,source:o})}case m.HLS_LIVE:case m.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return v(o),new Mr({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case m.MPEG:{const o=this.applyFailoverHost(t[e]);return v(o),new Or({...n,source:o})}case m.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return v(o),new Ea({...n,source:o,config:{...Kr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case m.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return v(o),new Ur({container:i,source:o,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case m.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return v(o),new Qs({connection:o,meta:r,container:i,source:t,format:e,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ge.CHROMECAST:ge.SCREEN}chooseFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ge.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return V(e)}}skipFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.next();case ge.CHROMECAST:return this.chromecastFormatsIterator.next();default:return V(e)}}handleNoFormatsError(e){switch(e){case ge.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ge.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return V(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const r=new URL(s);return r.host=t,r.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([s,r])=>[s,i(r)]))}initProviderErrorHandling(){const e=new ee;let t=!1,i=0;return e.add(O(this.providerOutput.error$,Xr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(T(s=>({id:`ProviderHangup:${s}`,category:P.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(oe(({to:r})=>r===l.PLAYING),Se()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const r=this.current$.getValue().destination;if(r===ge.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ge.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===P.NETWORK,o=s.category===P.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o;d&&!o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(r??ge.SCREEN)}})),e}}const en=5e3,es="one_video_throughput",ts="one_video_rtt",Ot=window.navigator.connection,is=()=>{const a=Ot?.downlink;if(A(a)&&a!==10)return a*1e3},ss=()=>{const a=Ot?.rtt;if(A(a)&&a!==3e3)return a},as=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Nt{throughput;rtt;subscription=new ee;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Nt.load(es)||(e.useBrowserEstimation?is():void 0)||en,i=Nt.load(ts)??(e.useBrowserEstimation?ss():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(i),this.rttAdjustedThroughput$=new g(as(t,i,e.rttPenaltyRequestSize)),this.throughput=wi.getSmoothedValue(t,-1,e),this.rtt=wi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=is();n&&this.throughput.next(n);const o=ss();A(o)&&this.rtt.next(o)};Ot&&"onchange"in Ot&&this.subscription.add(C(Ot,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{mi.set(es,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{mi.set(ts,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(De({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(T(({throughput:s,rtt:r})=>as(s,r,e.rttPenaltyRequestSize)),oe(s=>{const r=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-r)/r>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ae();const s=new ee;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(C(e,"progress").pipe(Se()).subscribe(r=>{t=r.loaded,i=ae()}));break;case 1:case 0:s.add(C(e,"loadstart").subscribe(()=>{t=0,i=ae()}));break}s.add(C(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=ae(),d=n-t,c=o-i;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,r=ae(),n=0,o=ae();const d=u=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},c=async({done:u,value:h})=>{if(u)!t&&this.addRawSpeed(s,ae()-r,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(ae()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=h.byteLength;else{const f=o-r;f&&this.addRawSpeed(n,f,1,t),n=h.byteLength,r=ae()}o=ae()}else s+=h.byteLength,n+=h.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ae()-o,this.concurrentDownloads.size),n=0,o=ae());await i?.read().then(c,d)}};this.concurrentDownloads.add(e),i?.read().then(c,d)}addRawSpeed(e,t,i=1,s=!1){if(Nt.sanityCheck(e,t,s)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=mi.get(e);if(A(t))return parseInt(t,10)??void 0}}const rs={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:$e.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$e.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:tt.VP9,androidPreferredFormat:ye.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}},tn=a=>({...Ns(a,rs),configName:[...a.configName??[],...rs.configName]});var ns=({seekState:a,position$:e})=>O(a.stateChangeEnded$.pipe(T(({to:t})=>t.state===G.None?void 0:(t.position??NaN)/1e3),oe(A)),e.pipe(oe(()=>a.getState().state===G.None))),sn=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return v(e,`Wrong container or containerId {${a.container}}`),e};const an=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(oe(s=>s.length>0),Se()).subscribe(s=>{s.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class dn{subscription=new ee;domContainer;providerContainer;chromecastInitializer;logger=new Fs;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;hasLiveOffsetByPaused=new g(!1);hasLiveOffsetByPausedTimer=0;desiredState={playbackState:new ne(l.STOPPED),seekState:new ne({state:G.None}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),internalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({}),cameraOrientation:new ne({x:0,y:0})};info={playbackState$:new g(l.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),currentQuality$:new g(void 0),isAutoQualityEnabled$:new g(!0),autoQualityLimitingAvailable$:new g(!1),autoQualityLimits$:new g({}),currentPlaybackRate$:new g(1),currentBuffer$:new g({start:0,end:0}),isBuffering$:new g(!0),isStalled$:new g(!1),isEnded$:new g(!1),isLooped$:new g(!1),isLive$:new g(void 0),canChangePlaybackSpeed$:new g(void 0),atLiveEdge$:new g(void 0),atLiveDurationEdge$:new g(void 0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),currentFormat$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),throughputEstimation$:new g(void 0),rttEstimation$:new g(void 0),videoBitrate$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),surface$:new g(We.NONE),chromecastState$:new g(pe.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0),availableSources$:new g(void 0),is3DVideo$:new g(!1),currentVideoSegmentLength$:new g(0),currentAudioSegmentLength$:new g(0)};events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x};experimental={element$:new g(void 0),tuningConfigName$:new g([]),enableDebugTelemetry$:new g(!1),dumpTelemetry:aa};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=tn(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Hs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Nt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const r=Reflect.get(t,i,s);return typeof r!="function"?r:(...n)=>{try{return r.apply(t,n)}catch(o){const d=n.map(h=>JSON.stringify(h,(p,f)=>{const S=typeof f;return["number","string","boolean"].includes(S)?f:f===null?null:`<${S}>`})),c=`Player.${String(i)}`,u=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:P.WTF,message:u,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=sn(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Zr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===l.STOPPED&&e.startTransitionTo(l.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==l.PLAYING&&t.startTransitionTo(l.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ei()?C(document,"visibilitychange").pipe(Se()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==l.PAUSED&&e.startTransitionTo(l.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==l.STOPPED&&e.startTransitionTo(l.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:G.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()===pe.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()===pe.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){v(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(oe(i=>i.length>0),Se()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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){v(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return an(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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 i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const s=i.getCameraRotation(),r=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+r.x,y:s.y+r.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(Q(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===G.None?void 0:t.position;return A(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(T(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e===l.STOPPED),Se()).subscribe(()=>{this.initedAt=ae(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case l.READY:this.events.ready$.next();break;case l.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case l.PAUSED:this.events.paused$.next();break;case l.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case l.PAUSED:this.events.willPause$.next();break;case l.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case l.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===G.Requested?this.desiredState.seekState.setState({...n,state:G.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:P.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===G.Applying&&(this.desiredState.seekState.setState({state:G.None}),this.events.seeked$.next())})).add(e.current$.pipe(T(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(T(n=>n.destination),de()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(T(n=>n.map(({quality:o})=>o).sort((o,d)=>ut(o)?1:ut(d)?-1:kt(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const d of n)d.fps&&(o[d.quality]=d.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?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(de()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(de()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(de()).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??{})})).add(e.providerOutput.currentBuffer$.pipe(T(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(De({hasLiveOffsetByPaused:O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(T(n=>n.to),de(),T(n=>n===l.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(De({atLiveEdge:De({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ns({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(T(({isLive:n,position:o,isLowLatency:d})=>{const c=this.getActiveLiveDelay(d);return n&&Math.abs(o)<c/1e3}),de(),Ft(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(T(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(De({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(T(({isLive:n,position:o,duration:d})=>n&&(Math.abs(d)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),de(),Ft(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(T(n=>n.muted),de()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(T(n=>n.volume),de()).subscribe(this.info.volume$)).add(ns({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(Zt(!0)),e.providerOutput.seekedEvent$.pipe(Zt(!1))).pipe(de()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(T(n=>({id:n?`No${n}`:"NoProviders",category:P.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(Se(),T(n=>n??ae()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Se(),T(()=>ae()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Se(),T(()=>ae()-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 g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new g(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oe(({to:n})=>n===l.PLAYING),Se()).subscribe(()=>i.next(!1)));let s=0;const r=O(e.providerOutput.isBuffering$,t,i).pipe(T(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),de());this.subscription.add(r.subscribe(n=>{n?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(O(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(O(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),u=this.chromecastInitializer.castState$.getValue();let h;u===pe.CONNECTED?h=We.SECOND_SCREEN:d?c?n?h=We.PIP:o?h=We.FULLSCREEN:h=We.INLINE:h=We.INVISIBLE:h=We.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(T(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ee;this.subscription.add(t),this.subscription.add(e.current$.pipe(de((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),Se()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=oi(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(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(T(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(){const e=this.providerContainer?.providerOutput;v(this.providerContainer),v(e),sa(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ia(t)),this.providerContainer.current$.subscribe(({type:t})=>Qt("provider",t)),e.duration$.subscribe(t=>Qt("duration",t)),e.availableVideoTracks$.pipe(oe(t=>!!t.length),Se()).subscribe(t=>Qt("tracks",t)),this.events.fatalError$.subscribe(new Ue("fatalError")),this.events.managedError$.subscribe(new Ue("managedError")),e.position$.subscribe(new Ue("position")),e.currentVideoTrack$.pipe(T(t=>t?.quality)).subscribe(new Ue("quality")),this.info.currentBuffer$.subscribe(new Ue("buffer")),e.isBuffering$.subscribe(new Ue("isBuffering"))].forEach(t=>this.subscription.add(t)),Qt("codecs",Wr())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:P.DOM,message:String(s)})})};this.subscription.add(O(C(document,"visibilitychange"),C(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",r=this.desiredState.playbackState.getState()===l.PLAYING,n=!!e&&!e?.released;s&&r?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const un=`@vkontakte/videoplayer-core@${Vs}`;export{pe as ChromecastState,Ti as HttpConnectionType,fn as Observable,l as PlaybackState,dn as Player,un as SDK_VERSION,pn as Subject,mn as Subscription,We as Surface,Vs as VERSION,gn as ValueSubject,m as VideoFormat,Sn as VideoQuality};
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 es=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 Xa(this.params.fov,this.params.orientation),this.cameraRotationManager=new Za(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(Zm,this.gl.VERTEX_SHADER),r=this.createShader(eb,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,l=t-a,u=e+r,c=t+a,d=e-r,h=t+a;return[s,n,o,l,u,c,d,h]}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 Vt=class{constructor(e){this.subscription=new hw;this.videoState=new L("stopped");this.elementSize$=new sb(void 0);this.textTracksManager=new be;this.droppedFramesManager=new qa;this.videoTracks$=new sb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Va;this.textTracks=[];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(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,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"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&T(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?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return sw(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new es(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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=ee(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(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ja({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=ie(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Zo.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,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(eu(u=>u.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(ow(lw),pw()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(re(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(me(this.video,t.playbackRate,r.playbackRateState$,a)),s(dw(this.video),this.elementSize$),s(ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){let c=[];this.audioTracks=[],this.textTracks=[];let d=this.player.getRepresentations();tb(d,"Manifest not loaded or empty");let h=Array.from(d.audio).sort((b,v)=>v.bitrate-b.bitrate),p=Array.from(d.video).sort((b,v)=>v.bitrate-b.bitrate),m=Array.from(d.text);if(!this.params.tuning.isAudioDisabled)for(let b of h){let v=Mm(b);v&&this.audioTracks.push({track:v,representation:b})}for(let b of p){let v=Dm(b);if(v){c.push({track:v,representation:b});let g=!this.params.tuning.isAudioDisabled&&Om(h,p,b);g&&this.audioRepresentations.set(b.id,g)}}this.videoTracks$.next(c);for(let b of m){let v=Bm(b);v&&this.textTracks.push({track:v,representation:b})}this.params.output.availableVideoTracks$.next(c.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));let S=this.selectVideoRepresentation();tb(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:Zo.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(ts(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$,uw(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);let p=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let S=d.id;!this.params.output.elementVisible$.getValue()&&p&&(S=this.videoTracks$.getValue().map(v=>v.representation).sort((v,g)=>g.bitrate-v.bitrate).filter(v=>{let g=ab(v),w=ab(d);if(g&&w)return ib(g,w)&&ib(g,m)}).map(v=>v.id)[0]),this.player.switchRepresentation("video",S).catch(n);let b=this.audioRepresentations.get(d.id);b&&this.player.switchRepresentation("audio",b.id).catch(n)}},a)),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(rb(),eu(u=>u&&this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(eu(({to:u})=>u==="ready"),rb());this.subscription.add(ts(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ts(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=ts(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cw(["init"])).pipe(nw(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,r=this.videoTracks$.getValue().find(({track:{id:d}})=>d===t)?.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),l=Math.max(r&&!e?this.audioRepresentations.get(r.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=lt(this.videoTracks$.getValue().map(({track:d})=>d),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?u??r:r??u;return c&&this.videoTracks$.getValue().find(({track:d})=>d===c)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ae(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zo.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),te(this.video)}};var Pi=class extends Vt{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)}};import{combine as nb,interval as fw,map as mw}from"@vkontakte/videoplayer-shared";var ki=class extends Vt{constructor(e){super(e),this.liveOffset=new Ye}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(nb({interval:fw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(nb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(mw(({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(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var ub=Oe(Da(),1);import{assertNever as wi,assertNonNullable as ob,debounce as bw,ErrorCategory as rs,filter as gw,isNonNullable as vw,isNullable as Sw,map as tu,merge as yw,Observable as Tw,observableFrom as Iw,Subscription as Ew,videoSizeToQuality as xw}from"@vkontakte/videoplayer-shared";var $e={};var mr=(i,e)=>new Tw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ai=class{constructor(e){this.subscription=new Ew;this.videoState=new L("initializing");this.textTracksManager=new be;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?.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:wi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:wi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:wi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:wi(e)}break;default:wi(t)}};this.video=ee(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(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),te(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:rs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,ub.default)(import("hls.js").then(a=>{e||($e.Hls=a.default,$e.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){ob($e.Hls,"hls.js not loaded"),this.hls=new $e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ob($e.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:rs.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ie(this.video),s=(u,c)=>this.subscription.add(u.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(_e(this.video,e.isLooped,r)),this.subscription.add(re(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(me(this.video,e.playbackRate,a.playbackRateState$,r)),s(ve(this.video),t.elementVisible$),this.subscription.add(mr(this.hls,$e.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:rs.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(mr(this.hls,$e.Events.MANIFEST_PARSED).pipe(tu(({levels:u})=>u.reduce((c,d)=>{let h=d.name||d.height.toString(10),{width:p,height:m}=d,S=ot(d.attrs.QUALITY??"")??xw({width:p,height:m});if(!S)return c;let b=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:S,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:b};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(mr(this.hls,$e.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang,S="internal";c.push({id:h,url:p,language:m,type:S})}e.internalTextTracks.startTransitionTo(c)}}),s(mr(this.hls,$e.Events.LEVEL_LOADING).pipe(tu(({url:u})=>Y(u))),t.hostname$),s(mr(this.hls,$e.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(at(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=mr(this.hls,$e.Events.LEVEL_SWITCHED).pipe(tu(({level:u})=>n(this.hls.levels[u])));o.pipe(gw(vw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(at(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(Sw(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.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 l=yw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Iw(["init"])).pipe(bw(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ae(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rs.DOM,thrown:t}))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var lb="X-Playback-Duration",ru=async i=>{let e=await Qe(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(lb)?parseInt(e.headers.get(lb),10):void 0};import{assertNever as Lw,combine as $w,debounce as Cw,ErrorCategory as as,filter as Dw,filterChanged as Mw,isNonNullable as db,isNullable as ss,map as pb,merge as Ow,observableFrom as Bw,Subscription as Vw,ValueSubject as su,VideoQuality as _w}from"@vkontakte/videoplayer-shared";var au=Oe(Ta(),1);import{videoSizeToQuality as Pw,getExponentialDelay as kw}from"@vkontakte/videoplayer-shared";var ww=i=>{let e=null;if(i.QUALITY&&(e=ot(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Pw({width:t,height:r})}return e??null},Aw=(i,e)=>{let t=i.split(`
92
+ `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,au.default)(o[1].split(",").map(b=>b.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=ww(u),h;u.BANDWIDTH&&(h=parseInt(u.BANDWIDTH,10)/1e3||void 0),!h&&u["AVERAGE-BANDWIDTH"]&&(h=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[b,v]=u.RESOLUTION.split("x").map(g=>parseInt(g,10));b&&v&&(m={width:b,height:v})}let S=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:S,bandwidth:h,size:m,fps:p})}if(l){let u=(0,au.default)(l[1].split(",").map(p=>p.split("=")).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,h=u.NAME;c&&d&&a.push({type:"internal",id:d,label:h,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Rw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),iu=0,cb=async(i,e=i,t)=>{let a=await(await Qe(i)).text();iu+=1;try{let{qualityManifests:s,textTracks:n}=Aw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(iu<=t.manifestRetryMaxCount)return await Rw(kw(iu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),cb(i,e,t)}return{qualityManifests:[],textTracks:[]}},is=cb;var Ri=class{constructor(e){this.subscription=new Vw;this.videoState=new L("stopped");this.textTracksManager=new be;this.manifests$=new su([]);this.liveOffset=new Ye;this.manifestStartTime$=new su(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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(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?.to==="playing"&&T(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?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Lw(t)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_w.INVARIANT,url:this.params.source.url},is(K(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:as.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:as.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Y(this.params.source.url)),this.maxSeekBackTime$=new su(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:as.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,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(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),s(ve(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(Mw(),pb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&db(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Y(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add($w({startTime:this.manifestStartTime$.pipe(Dw(db)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(pb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:h})=>({id:l,quality:u,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Ow(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Bw(["init"])).pipe(Cw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(ss(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:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ru(n).then(o=>{if(!ss(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(ss(l)||!isFinite(l))try{Qe(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();ru(d).then(h=>{ss(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:as.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()}};import{assertNever as Nw,debounce as Fw,ErrorCategory as nu,fromEvent as ou,isNonNullable as qw,isNullable as Uw,map as Hw,merge as hb,observableFrom as fb,Subscription as jw,ValueSubject as Gw,VideoQuality as Yw,isIOS as Ww}from"@vkontakte/videoplayer-shared";var Li=class{constructor(e){this.subscription=new jw;this.videoState=new L("stopped");this.textTracksManager=new be;this.manifests$=new Gw([]);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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),T(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?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Nw(t)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Yw.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(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),is(K(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:nu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:nu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));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(_e(this.video,t.isLooped,r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&qw(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(p=>p.id===d);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Y(h.url));let p=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(p!==m){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(p),S.playbackRate=p)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Hw(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:h})=>({id:l,quality:u,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Ww()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(hb(ou(o,"addtrack"),ou(o,"removetrack"),ou(o,"change"),fb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=hb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fb(["init"])).pipe(Fw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(Uw(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:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Qw,assertNonNullable as mb,debounce as zw,ErrorCategory as bb,isHigher as Kw,isHigherOrEqual as Jw,isInvariantQuality as gb,isLowerOrEqual as Xw,isNonNullable as Zw,merge as eA,observableFrom as tA,Subscription as rA}from"@vkontakte/videoplayer-shared";var $i=class{constructor(e){this.subscription=new rA;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new be;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.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"),T(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:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(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?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Qw(e)}};this.params=e,this.video=ee(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:bb.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,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(_e(this.video,t.isLooped,r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),s(ve(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Zw(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=eA(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,tA(["init"])).pipe(zw(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),te(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;mb(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];mb(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ii(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bb.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!gb(o.track.quality)&&Xw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Jw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!gb(u.track.quality)&&Kw(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=lt(a,{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})}};import{assertNever as Sb,debounce as nA,merge as yb,observableFrom as oA,Subscription as uA,map as Tb,ValueSubject as lA,ErrorCategory as lu,VideoQuality as cA}from"@vkontakte/videoplayer-shared";import{ErrorCategory as iA}from"@vkontakte/videoplayer-shared";var vb=["stun:videostun.mycdn.me:80"],aA=1e3,sA=3,uu=()=>null,ns=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=uu;this.externalStopCallback=uu;this.externalErrorCallback=uu;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:vb}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:iA.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await 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{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),aA)}normalizeOptions(e={}){let t={stunServerList:vb,maxRetryNumber:sA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ci=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new lA(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"),T(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"),T(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?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Sb(e)}};this.subscription=new uA,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ee(e.container),this.liveStreamClient=new ns(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),te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:lu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};yb(this.videoState.stateChangeStarted$.pipe(Tb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tb(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ie(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(ve(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(()=>{this.videoState.getTransition()?.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(re(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 Sb(n.to)}},r)).add(yb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,oA(["init"])).pipe(nA(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(Y(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:cA.INVARIANT}),this.video.srcObject=e,T(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:lu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Di=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}};import{assertNever as Oi,assertNonNullable as ft,ErrorCategory as ls,filter as EA,isNonNullable as $b,isNullable as xA,map as PA,merge as kA,once as wA,Subject as Ce,Subscription as Cb,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{assertNever as us,CurrentClientDevice as hA,getCurrentBrowser as fA}from"@vkontakte/videoplayer-shared";var Ib=fA().device===hA.Android,os=document.createElement("video"),mA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',bA='video/mp4; codecs="hev1.1.6.L93.B0"',Eb='video/webm; codecs="vp09.00.10.08"',xb='video/webm; codecs="av01.0.00M.08"',gA='audio/mp4; codecs="mp4a.40.2"',vA='audio/webm; codecs="opus"',_t={mms:za(),mse:Gm(),hls:!!(os.canPlayType?.("application/x-mpegurl")||os.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!os.canPlayType?.("video/mp4"),webm:!!os.canPlayType?.("video/webm"),cmaf:!0},Fe={h264:!!Xe()?.isTypeSupported?.(mA),h265:!!Xe()?.isTypeSupported?.(bA),vp9:!!Xe()?.isTypeSupported?.(Eb),av1:!!Xe()?.isTypeSupported?.(xb),aac:!!Xe()?.isTypeSupported?.(gA),opus:!!Xe()?.isTypeSupported?.(vA)},Mi=(Fe.h264||Fe.h265)&&Fe.aac,Nt,SA=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:xb}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Eb}})]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{SA()}catch(i){console.error(i)}var br=_t.hls&&Se.mp4,Pb=()=>Object.keys(Fe).filter(i=>Fe[i]),kb=(i,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Se.mp4&&Mi;case"DASH_WEBM":return r&&Se.webm&&Fe.vp9&&Fe.opus;case"DASH_WEBM_AV1":return r&&Se.webm&&Fe.av1&&Fe.opus;case"DASH_LIVE":return _t.mse&&Se.mp4&&Mi;case"DASH_LIVE_CMAF":return r&&Se.mp4&&Mi&&Se.cmaf;case"DASH_ONDEMAND":return r&&Se.mp4&&Mi;case"HLS":case"HLS_ONDEMAND":return br||e&&_t.mse&&Se.mp4&&Mi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return br;case"MPEG":return Se.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Fe.h264&&(Se.mp4||Se.webm);default:return us(a)}})},ht=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 Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:us(i)}return[e,t]},wb=({webmCodec:i,androidPreferredFormat:e})=>{if(Ib)switch(e){case"mpeg":return["MPEG",...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...ht(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...ht(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ht(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ht(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:us(e)}return br?[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Ab=({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(Ib)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:us(i)}else br?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},cu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as yA,map as Rb,Subscription as TA,Subject as IA}from"@vkontakte/videoplayer-shared";var Lb=i=>new yA(e=>{let t=new TA,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Rb(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Rb(({type:u})=>u!==void 0)),n=new IA,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var AA={chunkDuration:5e3,maxParallelRequests:5},Bi=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),currentVideoTrack$:new M(void 0),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),availableVideoTracks$:new M([]),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Ce,warning$:new Ce,willSeekEvent$:new Ce,seekedEvent$:new Ce,loopedEvent$:new Ce,endedEvent$:new Ce,firstBytesEvent$:new Ce,firstFrameEvent$:new Ce,canplay$:new Ce,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1)};this.subscription=new Cb;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=kb([...Ab(this.params.tuning),...wb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>$b(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 Di(s);let n=[...cu(!0),...cu(!1)];this.chromecastFormatsIterator=new Di(n.filter(o=>$b(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(xA(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ls.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 Oi(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]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ft(o),new Pi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ft(o),new ki({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return ft(o),br||!this.params.tuning.useHlsJs?new Li({...n,source:o}):new Ai({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ft(o),new Ri({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ft(o),new $i({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ft(o),new Hf({...n,source:o,config:{...AA,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ft(o),new Ci({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 Oi(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 ft(o),new Nr({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 Oi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Oi(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 Oi(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{...e,url:r(e.url)}}return(0,Db.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Cb,t=!1,r=0;return e.add(kA(this.providerOutput.error$,Lb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(PA(a=>({id:`ProviderHangup:${a}`,category:ls.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(EA(({to:s})=>s==="playing"),wA()).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===ls.NETWORK,o=a.category===ls.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};import{fromEvent as cs,once as RA,combine as LA,Subscription as Mb,ValueSubject as du,map as $A,filter as CA,isNonNullable as ds,now as he,safeStorage as pu}from"@vkontakte/videoplayer-shared";var DA=5e3,Ob="one_video_throughput",Bb="one_video_rtt",Vi=window.navigator.connection,Vb=()=>{let i=Vi?.downlink;if(ds(i)&&i!==10)return i*1e3},_b=()=>{let i=Vi?.rtt;if(ds(i)&&i!==3e3)return i},Nb=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},hu=class i{constructor(e){this.subscription=new Mb;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Ob)||(e.useBrowserEstimation?Vb():void 0)||DA,r=i.load(Bb)??(e.useBrowserEstimation?_b():void 0)??0;if(this.throughput$=new du(t),this.rtt$=new du(r),this.rttAdjustedThroughput$=new du(Nb(t,r,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Vb();n&&this.throughput.next(n);let o=_b();ds(o)&&this.rtt.next(o)};Vi&&"onchange"in Vi&&this.subscription.add(cs(Vi,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{pu.set(Ob,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{pu.set(Bb,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(LA({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($A(({throughput:a,rtt:s})=>Nb(a,s,e.rttPenaltyRequestSize)),CA(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=he(),a=new Mb;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(cs(e,"progress").pipe(RA()).subscribe(s=>{t=s.loaded,r=he()}));break;case 1:case 0:a.add(cs(e,"loadstart").subscribe(()=>{t=0,r=he()}));break}a.add(cs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=he(),l=n-t,u=o-r;this.addRawSpeed(l,u,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=he(),n=0,o=he(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,he()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let p=o-s;p&&this.addRawSpeed(n,p,1,t),n=d.byteLength,s=he()}o=he()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}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){let t=pu.get(e);if(ds(t))return parseInt(t,10)??void 0}},Fb=hu;import{fillWithDefault as MA,VideoQuality as qb}from"@vkontakte/videoplayer-shared";var Ub={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:qb.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:qb.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}},Hb=i=>({...MA(i,Ub),configName:[...i.configName??[],...Ub.configName]});import{assertNonNullable as ps,combine as hs,ErrorCategory as fs,filter as _i,filterChanged as ye,fromEvent as mu,isNonNullable as qA,isNullable as UA,Logger as HA,map as C,mapTo as Wb,merge as mt,now as ms,once as Ze,Subject as N,Subscription as Qb,tap as zb,ValueSubject as P,isHigher as jA,isInvariantQuality as Kb}from"@vkontakte/videoplayer-shared";import{merge as OA,map as BA,filter as jb,isNonNullable as VA}from"@vkontakte/videoplayer-shared";var fu=({seekState:i,position$:e})=>OA(i.stateChangeEnded$.pipe(BA(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),jb(VA)),e.pipe(jb(()=>i.getState().state==="none")));import{assertNonNullable as _A}from"@vkontakte/videoplayer-shared";var Gb=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return _A(e,`Wrong container or containerId {${i.container}}`),e};import{filter as NA,once as FA}from"@vkontakte/videoplayer-shared";var Yb=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(NA(a=>a.length>0),FA()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var bs=class{constructor(e={configName:[]}){this.subscription=new Qb;this.logger=new HA;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableQualities$:new P([]),availableQualitiesFps$:new P({}),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Lf};if(this.initLogs(),this.tuning=Hb(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Yi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Fb(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 l=n.map(d=>JSON.stringify(d,(h,p)=>{let m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:fs.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Gb(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Bi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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&&!Qr()?mu(document,"visibilitychange").pipe(Ze()).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){ps(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(_i(r=>r.length>0),Ze()).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){ps(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Yb(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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(UA(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return qA(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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(mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(_i(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=ms(),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({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:fs.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(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>Kb(o)?1:Kb(l)?-1:jA(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.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?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).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??{})})).add(e.providerOutput.currentBuffer$.pipe(C(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(hs({hasLiveOffsetByPaused:mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),ye(),C(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(hs({atLiveEdge:hs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:fu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),ye(),zb(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(hs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),zb(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),ye()).subscribe(this.info.volume$)).add(fu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(mt(e.providerOutput.endedEvent$.pipe(Wb(!0)),e.providerOutput.seekedEvent$.pipe(Wb(!1))).pipe(ye()).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(C(n=>({id:n?`No${n}`:"NoProviders",category:fs.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(Ze(),C(n=>n??ms()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),C(()=>ms()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),C(()=>ms()-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 P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(_i(({to:n})=>n==="playing"),Ze()).subscribe(()=>r.next(!1)));let a=0,s=mt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),ye());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(mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(mt(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(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?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(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Qb;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(_i(r=>r.length>0),Ze()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=lt(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(mt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(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(){let e=this.providerContainer?.providerOutput;ps(this.providerContainer),ps(e),Rf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Af(t)),this.providerContainer.current$.subscribe(({type:t})=>Hr("provider",t)),e.duration$.subscribe(t=>Hr("duration",t)),e.availableVideoTracks$.pipe(_i(t=>!!t.length),Ze()).subscribe(t=>Hr("tracks",t)),this.events.fatalError$.subscribe(new J("fatalError")),this.events.managedError$.subscribe(new J("managedError")),e.position$.subscribe(new J("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new J("quality")),this.info.currentBuffer$.subscribe(new J("buffer")),e.isBuffering$.subscribe(new J("isBuffering"))].forEach(t=>this.subscription.add(t)),Hr("codecs",Pb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:fs.DOM,message:String(a)})})};this.subscription.add(mt(mu(document,"visibilitychange"),mu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!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}};import{Subscription as G1,Observable as Y1,Subject as W1,ValueSubject as Q1,VideoQuality as z1}from"@vkontakte/videoplayer-shared";var K1=`@vkontakte/videoplayer-core@${vu}`;export{ji as ChromecastState,Es as HttpConnectionType,Y1 as Observable,le as PlaybackState,bs as Player,K1 as SDK_VERSION,W1 as Subject,G1 as Subscription,xs as Surface,vu as VERSION,Q1 as ValueSubject,gt as VideoFormat,z1 as VideoQuality};