@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/es2018.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 y,Subject as R,Subscription as ie,isNonNullable as L,ErrorCategory as _,isNullable as Q,fromEvent as I,assertNever as U,merge as N,tap as gi,map as $,observableFrom as Oe,filterChanged as he,assertNonNullable as P,debounce as Ke,getHighestQuality as fd,timeout as pd,getCurrentBrowser as Mr,CurrentClientBrowser as Nn,combine as Ie,once as Te,mapTo as es,filter as ce,VideoQuality as Pe,now as oe,assertNotEmptyArray as md,videoSizeToQuality as kt,isInvariantQuality as Pt,isHigher as Zt,isLower as zi,isHigherOrEqual as br,isLowerOrEqual as ts,interval as pi,Observable as Br,videoQualityToHeight as vd,abortable as we,getExponentialDelay as Qi,throttle as gd,observeElementSize as Sd,isIOS as bd,CurrentClientDevice as yd,safeStorage as Is,fillWithDefault as Td,Logger as Ed}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as ig,Subject as sg,Subscription as rg,ValueSubject as ag,VideoQuality as ng}from"@vkontakte/videoplayer-shared/es2018.esm.js";const $d="2.0.103";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var ye;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ye||(ye={}));var ge;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ge||(ge={}));var yr;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(yr||(yr={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var Ze;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip",i.INVISIBLE="invisible"})(Ze||(Ze={}));var Ad=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class wd{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(ge.NOT_AVAILABLE),this.errorEvent$=new R,this.realCastState$=new y(ge.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=L((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Ad("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){L(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),s=cast.framework.CastContext.getInstance();this.subscription.add(I(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return U(r.sessionState)}})).add(N(I(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Oe([s.getCastState()])).pipe(he(),$(kd),gi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ge.CONNECTED,o=L(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),c=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(Q(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ge.CONNECTED?L(this.connection$.getValue())?ge.CONNECTED:ge.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const kd=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return U(i)}};var Cs=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Nr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var at=function(i){try{return!!i()}catch(e){return!0}},Pd=at,us=!Pd(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Fn=us,Vn=Function.prototype,Tr=Vn.call,Ld=Fn&&Vn.bind.bind(Tr,Tr),nt=Fn?Ld:function(i){return function(){return Tr.apply(i,arguments)}},Un=nt,Dd=Un({}.toString),xd=Un("".slice),cs=function(i){return xd(Dd(i),8,-1)},_d=nt,Rd=at,Id=cs,Os=Object,Cd=_d("".split),Od=Rd(function(){return!Os("z").propertyIsEnumerable(0)})?function(i){return Id(i)=="String"?Cd(i,""):Os(i)}:Os,hs=function(i){return i==null},Md=hs,Bd=TypeError,Fr=function(i){if(Md(i))throw Bd("Can't call method on "+i);return i},Nd=Od,Fd=Fr,Ti=function(i){return Nd(Fd(i))},si={},Ri=function(i){return i&&i.Math==Math&&i},Ue=Ri(typeof globalThis=="object"&&globalThis)||Ri(typeof window=="object"&&window)||Ri(typeof self=="object"&&self)||Ri(typeof Cs=="object"&&Cs)||function(){return this}()||Cs||Function("return this")(),Er=typeof document=="object"&&document.all,Vd=typeof Er=="undefined"&&Er!==void 0,Hn={all:Er,IS_HTMLDDA:Vd},Gn=Hn,Ud=Gn.all,Me=Gn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Ud}:function(i){return typeof i=="function"},Hd=Ue,Gd=Me,va=Hd.WeakMap,Yd=Gd(va)&&/native code/.test(String(va)),ga=Me,Yn=Hn,qd=Yn.all,Dt=Yn.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ga(i)||i===qd}:function(i){return typeof i=="object"?i!==null:ga(i)},jd=at,xt=!jd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ri={},Wd=Ue,Sa=Dt,$r=Wd.document,zd=Sa($r)&&Sa($r.createElement),qn=function(i){return zd?$r.createElement(i):{}},Qd=xt,Kd=at,Jd=qn,jn=!Qd&&!Kd(function(){return Object.defineProperty(Jd("div"),"a",{get:function(){return 7}}).a!=7}),Xd=xt,Zd=at,Wn=Xd&&Zd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),el=Dt,tl=String,il=TypeError,_t=function(i){if(el(i))return i;throw il(tl(i)+" is not an object")},sl=us,Ii=Function.prototype.call,ot=sl?Ii.bind(Ii):function(){return Ii.apply(Ii,arguments)},Vr={},Ms=Vr,Bs=Ue,rl=Me,ba=function(i){return rl(i)?i:void 0},Ur=function(i,e){return arguments.length<2?ba(Ms[i])||ba(Bs[i]):Ms[i]&&Ms[i][e]||Bs[i]&&Bs[i][e]},al=nt,Hr=al({}.isPrototypeOf),nl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zn=Ue,Ns=nl,ya=zn.process,Ta=zn.Deno,Ea=ya&&ya.versions||Ta&&Ta.version,$a=Ea&&Ea.v8,Fe,is;$a&&(Fe=$a.split("."),is=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!is&&Ns&&(Fe=Ns.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Ns.match(/Chrome\/(\d+)/),Fe&&(is=+Fe[1])));var ol=is,Aa=ol,dl=at,ll=Ue,ul=ll.String,Qn=!!Object.getOwnPropertySymbols&&!dl(function(){var i=Symbol();return!ul(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Aa&&Aa<41}),cl=Qn,Kn=cl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",hl=Ur,fl=Me,pl=Hr,ml=Kn,vl=Object,Jn=ml?function(i){return typeof i=="symbol"}:function(i){var e=hl("Symbol");return fl(e)&&pl(e.prototype,vl(i))},gl=String,Gr=function(i){try{return gl(i)}catch(e){return"Object"}},Sl=Me,bl=Gr,yl=TypeError,Yr=function(i){if(Sl(i))return i;throw yl(bl(i)+" is not a function")},Tl=Yr,El=hs,fs=function(i,e){var t=i[e];return El(t)?void 0:Tl(t)},Fs=ot,Vs=Me,Us=Dt,$l=TypeError,Al=function(i,e){var t,s;if(e==="string"&&Vs(t=i.toString)&&!Us(s=Fs(t,i))||Vs(t=i.valueOf)&&!Us(s=Fs(t,i))||e!=="string"&&Vs(t=i.toString)&&!Us(s=Fs(t,i)))return s;throw $l("Can't convert object to primitive value")},Xn={exports:{}},wa=Ue,wl=Object.defineProperty,kl=function(i,e){try{wl(wa,i,{value:e,configurable:!0,writable:!0})}catch(t){wa[i]=e}return e},Pl=Ue,Ll=kl,ka="__core-js_shared__",Dl=Pl[ka]||Ll(ka,{}),Zn=Dl,Pa=Zn;(Xn.exports=function(i,e){return Pa[i]||(Pa[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eo=Xn.exports,xl=Fr,_l=Object,ps=function(i){return _l(xl(i))},Rl=nt,Il=ps,Cl=Rl({}.hasOwnProperty),dt=Object.hasOwn||function(e,t){return Cl(Il(e),t)},Ol=nt,Ml=0,Bl=Math.random(),Nl=Ol(1 .toString),to=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Nl(++Ml+Bl,36)},Fl=Ue,Vl=eo,La=dt,Ul=to,Hl=Qn,Gl=Kn,Jt=Fl.Symbol,Hs=Vl("wks"),Yl=Gl?Jt.for||Jt:Jt&&Jt.withoutSetter||Ul,He=function(i){return La(Hs,i)||(Hs[i]=Hl&&La(Jt,i)?Jt[i]:Yl("Symbol."+i)),Hs[i]},ql=ot,Da=Dt,xa=Jn,jl=fs,Wl=Al,zl=He,Ql=TypeError,Kl=zl("toPrimitive"),Jl=function(i,e){if(!Da(i)||xa(i))return i;var t=jl(i,Kl),s;if(t){if(e===void 0&&(e="default"),s=ql(t,i,e),!Da(s)||xa(s))return s;throw Ql("Can't convert object to primitive value")}return e===void 0&&(e="number"),Wl(i,e)},Xl=Jl,Zl=Jn,qr=function(i){var e=Xl(i,"string");return Zl(e)?e:e+""},eu=xt,tu=jn,iu=Wn,Ci=_t,_a=qr,su=TypeError,Gs=Object.defineProperty,ru=Object.getOwnPropertyDescriptor,Ys="enumerable",qs="configurable",js="writable";ri.f=eu?iu?function(e,t,s){if(Ci(e),t=_a(t),Ci(s),typeof e=="function"&&t==="prototype"&&"value"in s&&js in s&&!s[js]){var r=ru(e,t);r&&r[js]&&(e[t]=s.value,s={configurable:qs in s?s[qs]:r[qs],enumerable:Ys in s?s[Ys]:r[Ys],writable:!1})}return Gs(e,t,s)}:Gs:function(e,t,s){if(Ci(e),t=_a(t),Ci(s),tu)try{return Gs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw su("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var ms=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},au=xt,nu=ri,ou=ms,Ei=au?function(i,e,t){return nu.f(i,e,ou(1,t))}:function(i,e,t){return i[e]=t,i},du=eo,lu=to,Ra=du("keys"),jr=function(i){return Ra[i]||(Ra[i]=lu(i))},Wr={},uu=Yd,io=Ue,cu=Dt,hu=Ei,Ws=dt,zs=Zn,fu=jr,pu=Wr,Ia="Object already initialized",Ar=io.TypeError,mu=io.WeakMap,ss,Si,rs,vu=function(i){return rs(i)?Si(i):ss(i,{})},gu=function(i){return function(e){var t;if(!cu(e)||(t=Si(e)).type!==i)throw Ar("Incompatible receiver, "+i+" required");return t}};if(uu||zs.state){var qe=zs.state||(zs.state=new mu);qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,ss=function(i,e){if(qe.has(i))throw Ar(Ia);return e.facade=i,qe.set(i,e),e},Si=function(i){return qe.get(i)||{}},rs=function(i){return qe.has(i)}}else{var Gt=fu("state");pu[Gt]=!0,ss=function(i,e){if(Ws(i,Gt))throw Ar(Ia);return e.facade=i,hu(i,Gt,e),e},Si=function(i){return Ws(i,Gt)?i[Gt]:{}},rs=function(i){return Ws(i,Gt)}}var Su={set:ss,get:Si,has:rs,enforce:vu,getterFor:gu},bu=us,so=Function.prototype,Ca=so.apply,Oa=so.call,yu=typeof Reflect=="object"&&Reflect.apply||(bu?Oa.bind(Ca):function(){return Oa.apply(Ca,arguments)}),Tu=cs,Eu=nt,ro=function(i){if(Tu(i)==="Function")return Eu(i)},ao={},no={},oo={}.propertyIsEnumerable,lo=Object.getOwnPropertyDescriptor,$u=lo&&!oo.call({1:2},1);no.f=$u?function(e){var t=lo(this,e);return!!t&&t.enumerable}:oo;var Au=xt,wu=ot,ku=no,Pu=ms,Lu=Ti,Du=qr,xu=dt,_u=jn,Ma=Object.getOwnPropertyDescriptor;ao.f=Au?Ma:function(e,t){if(e=Lu(e),t=Du(t),_u)try{return Ma(e,t)}catch(s){}if(xu(e,t))return Pu(!wu(ku.f,e,t),e[t])};var Ru=at,Iu=Me,Cu=/#|\.prototype\./,$i=function(i,e){var t=Mu[Ou(i)];return t==Nu?!0:t==Bu?!1:Iu(e)?Ru(e):!!e},Ou=$i.normalize=function(i){return String(i).replace(Cu,".").toLowerCase()},Mu=$i.data={},Bu=$i.NATIVE="N",Nu=$i.POLYFILL="P",Fu=$i,Ba=ro,Vu=Yr,Uu=us,Hu=Ba(Ba.bind),uo=function(i,e){return Vu(i),e===void 0?i:Uu?Hu(i,e):function(){return i.apply(e,arguments)}},Oi=Ue,Gu=yu,Yu=ro,qu=Me,ju=ao.f,Wu=Fu,Yt=Vr,zu=uo,qt=Ei,Na=dt,Qu=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Gu(i,this,arguments)};return e.prototype=i.prototype,e},vs=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Oi:r?Oi[t]:(Oi[t]||{}).prototype,o=s?Yt:Yt[t]||qt(Yt,t,{})[t],u=o.prototype,d,c,l,h,f,v,m,g,S;for(h in e)d=Wu(s?h:t+(r?".":"#")+h,i.forced),c=!d&&n&&Na(n,h),v=o[h],c&&(i.dontCallGetSet?(S=ju(n,h),m=S&&S.value):m=n[h]),f=c&&m?m:e[h],!(c&&typeof v==typeof f)&&(i.bind&&c?g=zu(f,Oi):i.wrap&&c?g=Qu(f):a&&qu(f)?g=Yu(f):g=f,(i.sham||f&&f.sham||v&&v.sham)&&qt(g,"sham",!0),qt(o,h,g),a&&(l=t+"Prototype",Na(Yt,l)||qt(Yt,l,{}),qt(Yt[l],h,f),i.real&&u&&(d||!u[h])&&qt(u,h,f)))},wr=xt,Ku=dt,co=Function.prototype,Ju=wr&&Object.getOwnPropertyDescriptor,zr=Ku(co,"name"),Xu=zr&&function(){}.name==="something",Zu=zr&&(!wr||wr&&Ju(co,"name").configurable),ec={EXISTS:zr,PROPER:Xu,CONFIGURABLE:Zu},ho={},tc=Math.ceil,ic=Math.floor,sc=Math.trunc||function(e){var t=+e;return(t>0?ic:tc)(t)},rc=sc,Qr=function(i){var e=+i;return e!==e||e===0?0:rc(e)},ac=Qr,nc=Math.max,oc=Math.min,dc=function(i,e){var t=ac(i);return t<0?nc(t+e,0):oc(t,e)},lc=Qr,uc=Math.min,cc=function(i){return i>0?uc(lc(i),9007199254740991):0},hc=cc,Kr=function(i){return hc(i.length)},fc=Ti,pc=dc,mc=Kr,Fa=function(i){return function(e,t,s){var r=fc(e),a=mc(r),n=pc(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},vc={includes:Fa(!0),indexOf:Fa(!1)},gc=nt,Qs=dt,Sc=Ti,bc=vc.indexOf,yc=Wr,Va=gc([].push),Tc=function(i,e){var t=Sc(i),s=0,r=[],a;for(a in t)!Qs(yc,a)&&Qs(t,a)&&Va(r,a);for(;e.length>s;)Qs(t,a=e[s++])&&(~bc(r,a)||Va(r,a));return r},fo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ec=Tc,$c=fo,Ac=Object.keys||function(e){return Ec(e,$c)},wc=xt,kc=Wn,Pc=ri,Lc=_t,Dc=Ti,xc=Ac;ho.f=wc&&!kc?Object.defineProperties:function(e,t){Lc(e);for(var s=Dc(t),r=xc(t),a=r.length,n=0,o;a>n;)Pc.f(e,o=r[n++],s[o]);return e};var _c=Ur,Rc=_c("document","documentElement"),Ic=_t,Cc=ho,Ua=fo,Oc=Wr,Mc=Rc,Bc=qn,Nc=jr,Ha=">",Ga="<",kr="prototype",Pr="script",po=Nc("IE_PROTO"),Ks=function(){},mo=function(i){return Ga+Pr+Ha+i+Ga+"/"+Pr+Ha},Ya=function(i){i.write(mo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Fc=function(){var i=Bc("iframe"),e="java"+Pr+":",t;return i.style.display="none",Mc.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(mo("document.F=Object")),t.close(),t.F},Mi,Ki=function(){try{Mi=new ActiveXObject("htmlfile")}catch(e){}Ki=typeof document!="undefined"?document.domain&&Mi?Ya(Mi):Fc():Ya(Mi);for(var i=Ua.length;i--;)delete Ki[kr][Ua[i]];return Ki()};Oc[po]=!0;var vo=Object.create||function(e,t){var s;return e!==null?(Ks[kr]=Ic(e),s=new Ks,Ks[kr]=null,s[po]=e):s=Ki(),t===void 0?s:Cc.f(s,t)},Vc=at,Uc=!Vc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Hc=dt,Gc=Me,Yc=ps,qc=jr,jc=Uc,qa=qc("IE_PROTO"),Lr=Object,Wc=Lr.prototype,go=jc?Lr.getPrototypeOf:function(i){var e=Yc(i);if(Hc(e,qa))return e[qa];var t=e.constructor;return Gc(t)&&e instanceof t?t.prototype:e instanceof Lr?Wc:null},zc=Ei,So=function(i,e,t,s){return s&&s.enumerable?i[e]=t:zc(i,e,t),i},Qc=at,Kc=Me,Jc=Dt,Xc=vo,ja=go,Zc=So,eh=He,Dr=eh("iterator"),bo=!1,st,Js,Xs;[].keys&&(Xs=[].keys(),"next"in Xs?(Js=ja(ja(Xs)),Js!==Object.prototype&&(st=Js)):bo=!0);var th=!Jc(st)||Qc(function(){var i={};return st[Dr].call(i)!==i});th?st={}:st=Xc(st);Kc(st[Dr])||Zc(st,Dr,function(){return this});var yo={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:bo},ih=He,sh=ih("toStringTag"),To={};To[sh]="z";var Jr=String(To)==="[object z]",rh=Jr,ah=Me,Ji=cs,nh=He,oh=nh("toStringTag"),dh=Object,lh=Ji(function(){return arguments}())=="Arguments",uh=function(i,e){try{return i[e]}catch(t){}},gs=rh?Ji:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=uh(e=dh(i),oh))=="string"?t:lh?Ji(e):(s=Ji(e))=="Object"&&ah(e.callee)?"Arguments":s},ch=Jr,hh=gs,fh=ch?{}.toString:function(){return"[object "+hh(this)+"]"},ph=Jr,mh=ri.f,vh=Ei,gh=dt,Sh=fh,bh=He,Wa=bh("toStringTag"),Eo=function(i,e,t,s){if(i){var r=t?i:i.prototype;gh(r,Wa)||mh(r,Wa,{configurable:!0,value:e}),s&&!ph&&vh(r,"toString",Sh)}},yh=yo.IteratorPrototype,Th=vo,Eh=ms,$h=Eo,Ah=si,wh=function(){return this},kh=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Th(yh,{next:Eh(+!s,t)}),$h(i,r,!1,!0),Ah[r]=wh,i},Ph=vs,Lh=ot,$o=ec,Dh=kh,xh=go,_h=Eo,za=So,Rh=He,Qa=si,Ao=yo,Ih=$o.PROPER;$o.CONFIGURABLE;Ao.IteratorPrototype;var Bi=Ao.BUGGY_SAFARI_ITERATORS,Zs=Rh("iterator"),Ka="keys",Ni="values",Ja="entries",Ch=function(){return this},Oh=function(i,e,t,s,r,a,n){Dh(t,e,s);var o=function(S){if(S===r&&h)return h;if(!Bi&&S in c)return c[S];switch(S){case Ka:return function(){return new t(this,S)};case Ni:return function(){return new t(this,S)};case Ja:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,c=i.prototype,l=c[Zs]||c["@@iterator"]||r&&c[r],h=!Bi&&l||o(r),f=e=="Array"&&c.entries||l,v,m,g;if(f&&(v=xh(f.call(new i)),v!==Object.prototype&&v.next&&(_h(v,u,!0,!0),Qa[u]=Ch)),Ih&&r==Ni&&l&&l.name!==Ni&&(d=!0,h=function(){return Lh(l,this)}),r)if(m={values:o(Ni),keys:a?h:o(Ka),entries:o(Ja)},n)for(g in m)(Bi||d||!(g in c))&&za(c,g,m[g]);else Ph({target:e,proto:!0,forced:Bi||d},m);return n&&c[Zs]!==h&&za(c,Zs,h,{name:r}),Qa[e]=h,m},Mh=function(i,e){return{value:i,done:e}},Bh=Ti,Xa=si,wo=Su;ri.f;var Nh=Oh,Fi=Mh,ko="Array Iterator",Fh=wo.set,Vh=wo.getterFor(ko);Nh(Array,"Array",function(i,e){Fh(this,{type:ko,target:Bh(i),index:0,kind:e})},function(){var i=Vh(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Fi(void 0,!0)):t=="keys"?Fi(s,!1):t=="values"?Fi(e[s],!1):Fi([s,e[s]],!1)},"values");Xa.Arguments=Xa.Array;var Uh=He,Hh=si,Gh=Uh("iterator"),Yh=Array.prototype,qh=function(i){return i!==void 0&&(Hh.Array===i||Yh[Gh]===i)},jh=gs,Za=fs,Wh=hs,zh=si,Qh=He,Kh=Qh("iterator"),Po=function(i){if(!Wh(i))return Za(i,Kh)||Za(i,"@@iterator")||zh[jh(i)]},Jh=ot,Xh=Yr,Zh=_t,ef=Gr,tf=Po,sf=TypeError,rf=function(i,e){var t=arguments.length<2?tf(i):e;if(Xh(t))return Zh(Jh(t,i));throw sf(ef(i)+" is not iterable")},af=ot,en=_t,nf=fs,of=function(i,e,t){var s,r;en(i);try{if(s=nf(i,"return"),!s){if(e==="throw")throw t;return t}s=af(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return en(s),t},df=uo,lf=ot,uf=_t,cf=Gr,hf=qh,ff=Kr,tn=Hr,pf=rf,mf=Po,sn=of,vf=TypeError,Xi=function(i,e){this.stopped=i,this.result=e},rn=Xi.prototype,gf=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=df(e,s),d,c,l,h,f,v,m,g=function(E){return d&&sn(d,"normal",E),new Xi(!0,E)},S=function(E){return r?(uf(E),o?u(E[0],E[1],g):u(E[0],E[1])):o?u(E,g):u(E)};if(a)d=i.iterator;else if(n)d=i;else{if(c=mf(i),!c)throw vf(cf(i)+" is not iterable");if(hf(c)){for(l=0,h=ff(i);h>l;l++)if(f=S(i[l]),f&&tn(rn,f))return f;return new Xi(!1)}d=pf(i,c)}for(v=a?i.next:d.next;!(m=lf(v,d)).done;){try{f=S(m.value)}catch(E){sn(d,"throw",E)}if(typeof f=="object"&&f&&tn(rn,f))return f}return new Xi(!1)},Sf=qr,bf=ri,yf=ms,Tf=function(i,e,t){var s=Sf(e);s in i?bf.f(i,s,yf(0,t)):i[s]=t},Ef=vs,$f=gf,Af=Tf;Ef({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $f(e,function(s,r){Af(t,s,r)},{AS_ENTRIES:!0}),t}});var wf=Vr,kf=wf.Object.fromEntries,Pf={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},Lf=Pf,Df=Ue,xf=gs,_f=Ei,an=si,Rf=He,nn=Rf("toStringTag");for(var er in Lf){var on=Df[er],tr=on&&on.prototype;tr&&xf(tr)!==nn&&_f(tr,nn,er),an[er]=an.Array}var If=kf,Cf=If,Of=Cf,Mf=Of,as=Nr(Mf),me;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(me||(me={}));var Ve=(i,e=0,t=me.OFFSET_P)=>{switch(t){case me.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case me.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case me.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:U(t)}return i};const dn=(i,e)=>{var t;switch(e){case me.OFFSET_P:return NaN;case me.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case me.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:U(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class ue{constructor(e){this.transitionStarted$=new R,this.transitionEnded$=new R,this.transitionUpdated$=new R,this.forceChanged$=new R,this.stateChangeStarted$=N(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=N(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||L(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Bf=i=>{switch(i){case b.MPEG:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return U(i)}};var V;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Nf=5,Ff=5,Vf=500,ln=7e3;class Uf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new ue(V.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==V.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case V.PLAYING:case V.PAUSED:case V.READY:break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}case p.PLAYING:{switch(s){case V.PLAYING:break;case V.PAUSED:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.READY:this.videoState.startTransitionTo(V.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}case p.PAUSED:{switch(s){case V.PLAYING:this.videoState.startTransitionTo(V.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case V.PAUSED:break;case V.READY:this.videoState.startTransitionTo(V.PAUSED),this.videoState.setState(V.PAUSED);break;case V.STOPPED:this.videoState.startTransitionTo(V.READY),this.prepare();break;default:U(s)}break}default:U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Bf(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 ie;this.subscription.add(e),this.subscription.add(N(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new R;e.add(r.pipe(Ke(Vf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(I(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===Y.Applying||Math.abs(o-a)>Nf)&&r.next(o),a=o})),e.add(I(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(I(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(I(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(I(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Ff&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:U(n)}}),t(I(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(I(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=N(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ke(0));t(s,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(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PAUSED||e===V.PLAYING)&&(this.videoState.setState(V.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===V.PLAYING||e===V.PAUSED)&&(this.videoState.setState(V.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===V.READY&&this.videoState.setState(V.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==V.STOPPED&&this.videoState.setState(V.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const c=s[e];P(c);const l=fd(Object.keys(c));P(l);const h=c[l];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const c=s[e];P(c),r=c.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.DASH_WEBM_AV1:{const c=s[e];P(c),r=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const c=s[e];P(c),r=c.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const c=s[e];P(c),r=Ve(c.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:c,thrown:l}),l}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return L(u)&&(o.metadata.title=u),L(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(pd(ln).subscribe(()=>a(`timeout(${ln})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Xr=i=>{i.removeAttribute("src"),i.load()},Hf=i=>{try{i.pause(),i.playbackRate=0,Xr(i),i.remove()}catch(e){console.error(e)}};class Gf{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const xr=window.WeakMap?new WeakMap:new Gf,Rt=i=>{let e=i.querySelector("video");const t=!!e;return e?Xr(e):(e=document.createElement("video"),i.appendChild(e)),xr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=i=>{const e=xr.get(i);xr.delete(i),e?Xr(i):Hf(i)},tt=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=Q(r),d=new ie;return r&&d.add(r.subscribe(c=>{const l=i.getState();s(c,l)&&i.setState(c)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},a)),d},Ai=(i,e,t)=>tt(e,()=>i.loop,s=>{L(s)&&(i.loop=s)},{onError:t}),Ct=(i,e,t,s)=>tt(e,()=>({muted:i.muted,volume:i.volume}),r=>{L(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),ai=(i,e,t,s)=>tt(e,()=>i.playbackRate,r=>{L(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Yf=i=>["__",i.language,i.label].join("|"),qf=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class mt{constructor(){this.available$=new R,this.current$=new y(void 0),this.error$=new R,this.subscription=new ie,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(tt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{L(a)&&this.setInternal(a)},{equal:(a,n)=>L(a)&&L(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(tt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{L(a)&&this.setExternal(a)},{equal:(a,n)=>L(a)&&L(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(tt(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(I(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(N(I(e,"addtrack"),I(e,"removetrack"),Oe(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),he((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(N(I(e,"change"),Oe(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),he()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(I(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,c,l,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((l=(c=o.target)===null||c===void 0?void 0:c.cues)!==null&&l!==void 0?l:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(I(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;L(t.align)&&(r.align=t.align),L(t.position)&&(r.position=t.position),L(t.size)&&(r.size=t.size),L(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(mt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:Yf(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0: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(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!qf(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){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.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 Zr{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Lo=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},un=i=>{const e=Lo(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},jf=i=>{const e=Lo(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Wf=3;var zf=(i,e,t=Wf)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const Ot=i=>{const e=A=>I(i,A).pipe(es(void 0)),s=N(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>I(i,A))).pipe($(A=>A.type==="ended"?i.readyState<2:i.readyState<3),he()),r=N(I(i,"progress"),I(i,"timeupdate")).pipe($(()=>zf(i.buffered,i.currentTime))),n=Mr().browser===Nn.Safari?Ie({play:e("play").pipe(Te()),playing:e("playing")}).pipe(es(void 0)):e("playing"),o=I(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=I(i,"ratechange").pipe($(()=>i.playbackRate)),d=I(i,"error").pipe(ce(()=>!!(i.error||i.played.length)),$(()=>{var A;const w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(A=i.error)!==null&&A!==void 0?A:void 0}})),c=I(i,"timeupdate").pipe($(()=>i.currentTime)),l=new R,h=.3;let f;c.subscribe(A=>{i.loop&&L(f)&&L(A)&&f>=i.duration-h&&A<=h&&l.next(f),f=A});const v=I(i,"enterpictureinpicture"),m=I(i,"leavepictureinpicture"),g=new y(jf(i));v.subscribe(()=>g.next(!0)),m.subscribe(()=>g.next(!1));const S=new y(un(i));return I(i,"fullscreenchange").pipe($(()=>un(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(ce(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:I(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:g,inFullscreen$:S}};var Ss=i=>{switch(i){case"mobile":return Pe.Q_144P;case"lowest":return Pe.Q_240P;case"low":return Pe.Q_360P;case"sd":case"medium":return Pe.Q_480P;case"hd":case"high":return Pe.Q_720P;case"fullhd":case"full":return Pe.Q_1080P;case"quadhd":case"quad":return Pe.Q_1440P;case"ultrahd":case"ultra":return Pe.Q_2160P}},Qf=vs,Kf=ps,Jf=Kr,Xf=Qr;Qf({target:"Array",proto:!0},{at:function(e){var t=Kf(this),s=Jf(t),r=Xf(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var Zf=Ur,Do=Zf,ep=Do,tp=ep("Array","at"),ip=tp,sp=ip,rp=sp,ap=rp,et=Nr(ap);let ea=!1,it={};const np=i=>{ea=i},op=()=>{it={}},dp=i=>{i(it)},Vi=(i,e)=>{var t;ea&&(it.meta=(t=it.meta)!==null&&t!==void 0?t:{},it.meta[i]=e)};class We{constructor(e){this.name=e}next(e){var t,s;if(!ea)return;it.series=(t=it.series)!==null&&t!==void 0?t:{};const r=(s=it.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),it.series[this.name]=r}}var At;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(At||(At={}));const lp=new We("best_bitrate"),up=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class cp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=oe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const hp='Assertion "ABR Tracks is empty array" failed',bs=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{var h,f,v,m,g;md(i,hp);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},A=E&&kt(E),w=s.considerPlaybackRate&&L(o)?o:1,k=i.filter(B=>!Pt(B.quality)).sort((B,x)=>Zt(B.quality,x.quality)?-1:1),q=(f=et(k,-1))===null||f===void 0?void 0:f.quality,j=(v=et(k,0))===null||v===void 0?void 0:v.quality,K=Q(r)||L(r.min)&&L(r.max)&&zi(r.max,r.min)||L(r.min)&&j&&Zt(r.min,j)||L(r.max)&&q&&zi(r.max,q),G=w*up(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),J={},M=k.filter(B=>(A?zi(B.quality,A):!0)?(L(t)&&isFinite(t)&&L(B.bitrate)?t-a>=B.bitrate*G:!0)?s.lazyQualitySwitch&&L(s.minBufferToSwitchUp)&&u&&!Pt(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Zt(B.quality,u.quality)?(J[B.quality]=At.Buffer,!1):!!c&&br(B.quality,c)?(J[B.quality]=At.DroppedFramesLimit,!1):K||(Q(r.max)||ts(B.quality,r.max))&&(Q(r.min)||br(B.quality,r.min))?!0:(J[B.quality]=At.FitsQualityLimits,!1):(J[B.quality]=At.FitsThroughput,!1):(J[B.quality]=At.FitsContainer,!1))[0];M&&M.bitrate&&lp.next(M.bitrate);const C=(m=M!=null?M:k[Math.ceil((k.length-1)/2)])!==null&&m!==void 0?m:i[0];C.quality!==((g=d==null?void 0:d.last)===null||g===void 0?void 0:g.quality)&&l({message:`
6
+ var ov=Object.create;var tl=Object.defineProperty;var uv=Object.getOwnPropertyDescriptor;var lv=Object.getOwnPropertyNames;var cv=Object.getPrototypeOf,dv=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var pv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of lv(e))!dv.call(i,a)&&a!==t&&tl(i,a,{get:()=>e[a],enumerable:!(r=uv(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?ov(cv(i)):{},pv(e||!i||!i.__esModule?tl(t,"default",{value:i,enumerable:!0}):t,i));var de=m((dL,ll)=>{"use strict";ll.exports=function(i){try{return!!i()}catch(e){return!0}}});var Lr=m((pL,cl)=>{"use strict";var yv=de();cl.exports=!yv(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var re=m((hL,hl)=>{"use strict";var dl=Lr(),pl=Function.prototype,Qs=pl.call,Tv=dl&&pl.bind.bind(Qs,Qs);hl.exports=dl?Tv:function(i){return function(){return Qs.apply(i,arguments)}}});var Jt=m((fL,ml)=>{"use strict";var fl=re(),Iv=fl({}.toString),Ev=fl("".slice);ml.exports=function(i){return Ev(Iv(i),8,-1)}});var gl=m((mL,bl)=>{"use strict";var xv=re(),Pv=de(),wv=Jt(),zs=Object,kv=xv("".split);bl.exports=Pv(function(){return!zs("z").propertyIsEnumerable(0)})?function(i){return wv(i)=="String"?kv(i,""):zs(i)}:zs});var Xt=m((bL,vl)=>{"use strict";vl.exports=function(i){return i==null}});var sa=m((gL,Sl)=>{"use strict";var Av=Xt(),Rv=TypeError;Sl.exports=function(i){if(Av(i))throw Rv("Can't call method on "+i);return i}});var Zt=m((vL,yl)=>{"use strict";var Lv=gl(),$v=sa();yl.exports=function(i){return Lv($v(i))}});var Ks=m((SL,Tl)=>{"use strict";Tl.exports=function(){}});var xt=m((yL,Il)=>{"use strict";Il.exports={}});var W=m((El,xl)=>{"use strict";var na=function(i){return i&&i.Math==Math&&i};xl.exports=na(typeof globalThis=="object"&&globalThis)||na(typeof window=="object"&&window)||na(typeof self=="object"&&self)||na(typeof global=="object"&&global)||function(){return this}()||El||Function("return this")()});var Xs=m((TL,Pl)=>{"use strict";var Js=typeof document=="object"&&document.all,Cv=typeof Js=="undefined"&&Js!==void 0;Pl.exports={all:Js,IS_HTMLDDA:Cv}});var q=m((IL,kl)=>{"use strict";var wl=Xs(),Dv=wl.all;kl.exports=wl.IS_HTMLDDA?function(i){return typeof i=="function"||i===Dv}:function(i){return typeof i=="function"}});var Ll=m((EL,Rl)=>{"use strict";var Mv=W(),Ov=q(),Al=Mv.WeakMap;Rl.exports=Ov(Al)&&/native code/.test(String(Al))});var Be=m((xL,Dl)=>{"use strict";var $l=q(),Cl=Xs(),Bv=Cl.all;Dl.exports=Cl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:$l(i)||i===Bv}:function(i){return typeof i=="object"?i!==null:$l(i)}});var Ve=m((PL,Ml)=>{"use strict";var Vv=de();Ml.exports=!Vv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var oa=m((wL,Bl)=>{"use strict";var _v=W(),Ol=Be(),Zs=_v.document,Nv=Ol(Zs)&&Ol(Zs.createElement);Bl.exports=function(i){return Nv?Zs.createElement(i):{}}});var en=m((kL,Vl)=>{"use strict";var Fv=Ve(),qv=de(),Uv=oa();Vl.exports=!Fv&&!qv(function(){return Object.defineProperty(Uv("div"),"a",{get:function(){return 7}}).a!=7})});var tn=m((AL,_l)=>{"use strict";var Hv=Ve(),jv=de();_l.exports=Hv&&jv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var we=m((RL,Nl)=>{"use strict";var Gv=Be(),Yv=String,Wv=TypeError;Nl.exports=function(i){if(Gv(i))return i;throw Wv(Yv(i)+" is not an object")}});var ie=m((LL,Fl)=>{"use strict";var Qv=Lr(),ua=Function.prototype.call;Fl.exports=Qv?ua.bind(ua):function(){return ua.apply(ua,arguments)}});var la=m(($L,ql)=>{"use strict";ql.exports={}});var Ue=m((CL,Hl)=>{"use strict";var rn=la(),an=W(),zv=q(),Ul=function(i){return zv(i)?i:void 0};Hl.exports=function(i,e){return arguments.length<2?Ul(rn[i])||Ul(an[i]):rn[i]&&rn[i][e]||an[i]&&an[i][e]}});var $r=m((DL,jl)=>{"use strict";var Kv=re();jl.exports=Kv({}.isPrototypeOf)});var Cr=m((ML,Gl)=>{"use strict";Gl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var nn=m((OL,Jl)=>{"use strict";var Kl=W(),sn=Cr(),Yl=Kl.process,Wl=Kl.Deno,Ql=Yl&&Yl.versions||Wl&&Wl.version,zl=Ql&&Ql.v8,ke,ca;zl&&(ke=zl.split("."),ca=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!ca&&sn&&(ke=sn.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=sn.match(/Chrome\/(\d+)/),ke&&(ca=+ke[1])));Jl.exports=ca});var on=m((BL,Zl)=>{"use strict";var Xl=nn(),Jv=de(),Xv=W(),Zv=Xv.String;Zl.exports=!!Object.getOwnPropertySymbols&&!Jv(function(){var i=Symbol();return!Zv(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Xl&&Xl<41})});var un=m((VL,ec)=>{"use strict";var eS=on();ec.exports=eS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ln=m((_L,tc)=>{"use strict";var tS=Ue(),rS=q(),iS=$r(),aS=un(),sS=Object;tc.exports=aS?function(i){return typeof i=="symbol"}:function(i){var e=tS("Symbol");return rS(e)&&iS(e.prototype,sS(i))}});var Dr=m((NL,rc)=>{"use strict";var nS=String;rc.exports=function(i){try{return nS(i)}catch(e){return"Object"}}});var He=m((FL,ic)=>{"use strict";var oS=q(),uS=Dr(),lS=TypeError;ic.exports=function(i){if(oS(i))return i;throw lS(uS(i)+" is not a function")}});var Mr=m((qL,ac)=>{"use strict";var cS=He(),dS=Xt();ac.exports=function(i,e){var t=i[e];return dS(t)?void 0:cS(t)}});var nc=m((UL,sc)=>{"use strict";var cn=ie(),dn=q(),pn=Be(),pS=TypeError;sc.exports=function(i,e){var t,r;if(e==="string"&&dn(t=i.toString)&&!pn(r=cn(t,i))||dn(t=i.valueOf)&&!pn(r=cn(t,i))||e!=="string"&&dn(t=i.toString)&&!pn(r=cn(t,i)))return r;throw pS("Can't convert object to primitive value")}});var Ae=m((HL,oc)=>{"use strict";oc.exports=!0});var cc=m((jL,lc)=>{"use strict";var uc=W(),hS=Object.defineProperty;lc.exports=function(i,e){try{hS(uc,i,{value:e,configurable:!0,writable:!0})}catch(t){uc[i]=e}return e}});var da=m((GL,pc)=>{"use strict";var fS=W(),mS=cc(),dc="__core-js_shared__",bS=fS[dc]||mS(dc,{});pc.exports=bS});var hn=m((YL,fc)=>{"use strict";var gS=Ae(),hc=da();(fc.exports=function(i,e){return hc[i]||(hc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:gS?"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 Or=m((WL,mc)=>{"use strict";var vS=sa(),SS=Object;mc.exports=function(i){return SS(vS(i))}});var Re=m((QL,bc)=>{"use strict";var yS=re(),TS=Or(),IS=yS({}.hasOwnProperty);bc.exports=Object.hasOwn||function(e,t){return IS(TS(e),t)}});var fn=m((zL,gc)=>{"use strict";var ES=re(),xS=0,PS=Math.random(),wS=ES(1 .toString);gc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+wS(++xS+PS,36)}});var K=m((KL,Sc)=>{"use strict";var kS=W(),AS=hn(),vc=Re(),RS=fn(),LS=on(),$S=un(),er=kS.Symbol,mn=AS("wks"),CS=$S?er.for||er:er&&er.withoutSetter||RS;Sc.exports=function(i){return vc(mn,i)||(mn[i]=LS&&vc(er,i)?er[i]:CS("Symbol."+i)),mn[i]}});var Ec=m((JL,Ic)=>{"use strict";var DS=ie(),yc=Be(),Tc=ln(),MS=Mr(),OS=nc(),BS=K(),VS=TypeError,_S=BS("toPrimitive");Ic.exports=function(i,e){if(!yc(i)||Tc(i))return i;var t=MS(i,_S),r;if(t){if(e===void 0&&(e="default"),r=DS(t,i,e),!yc(r)||Tc(r))return r;throw VS("Can't convert object to primitive value")}return e===void 0&&(e="number"),OS(i,e)}});var pa=m((XL,xc)=>{"use strict";var NS=Ec(),FS=ln();xc.exports=function(i){var e=NS(i,"string");return FS(e)?e:e+""}});var Pt=m(wc=>{"use strict";var qS=Ve(),US=en(),HS=tn(),ha=we(),Pc=pa(),jS=TypeError,bn=Object.defineProperty,GS=Object.getOwnPropertyDescriptor,gn="enumerable",vn="configurable",Sn="writable";wc.f=qS?HS?function(e,t,r){if(ha(e),t=Pc(t),ha(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Sn in r&&!r[Sn]){var a=GS(e,t);a&&a[Sn]&&(e[t]=r.value,r={configurable:vn in r?r[vn]:a[vn],enumerable:gn in r?r[gn]:a[gn],writable:!1})}return bn(e,t,r)}:bn:function(e,t,r){if(ha(e),t=Pc(t),ha(r),US)try{return bn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw jS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=m((e$,kc)=>{"use strict";kc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var wt=m((t$,Ac)=>{"use strict";var YS=Ve(),WS=Pt(),QS=Br();Ac.exports=YS?function(i,e,t){return WS.f(i,e,QS(1,t))}:function(i,e,t){return i[e]=t,i}});var fa=m((r$,Lc)=>{"use strict";var zS=hn(),KS=fn(),Rc=zS("keys");Lc.exports=function(i){return Rc[i]||(Rc[i]=KS(i))}});var ma=m((i$,$c)=>{"use strict";$c.exports={}});var En=m((a$,Mc)=>{"use strict";var JS=Ll(),Dc=W(),XS=Be(),ZS=wt(),yn=Re(),Tn=da(),ey=fa(),ty=ma(),Cc="Object already initialized",In=Dc.TypeError,ry=Dc.WeakMap,ba,Vr,ga,iy=function(i){return ga(i)?Vr(i):ba(i,{})},ay=function(i){return function(e){var t;if(!XS(e)||(t=Vr(e)).type!==i)throw In("Incompatible receiver, "+i+" required");return t}};JS||Tn.state?(Le=Tn.state||(Tn.state=new ry),Le.get=Le.get,Le.has=Le.has,Le.set=Le.set,ba=function(i,e){if(Le.has(i))throw In(Cc);return e.facade=i,Le.set(i,e),e},Vr=function(i){return Le.get(i)||{}},ga=function(i){return Le.has(i)}):(kt=ey("state"),ty[kt]=!0,ba=function(i,e){if(yn(i,kt))throw In(Cc);return e.facade=i,ZS(i,kt,e),e},Vr=function(i){return yn(i,kt)?i[kt]:{}},ga=function(i){return yn(i,kt)});var Le,kt;Mc.exports={set:ba,get:Vr,has:ga,enforce:iy,getterFor:ay}});var xn=m((s$,_c)=>{"use strict";var sy=Lr(),Vc=Function.prototype,Oc=Vc.apply,Bc=Vc.call;_c.exports=typeof Reflect=="object"&&Reflect.apply||(sy?Bc.bind(Oc):function(){return Bc.apply(Oc,arguments)})});var Pn=m((n$,Nc)=>{"use strict";var ny=Jt(),oy=re();Nc.exports=function(i){if(ny(i)==="Function")return oy(i)}});var Hc=m(Uc=>{"use strict";var Fc={}.propertyIsEnumerable,qc=Object.getOwnPropertyDescriptor,uy=qc&&!Fc.call({1:2},1);Uc.f=uy?function(e){var t=qc(this,e);return!!t&&t.enumerable}:Fc});var wn=m(Gc=>{"use strict";var ly=Ve(),cy=ie(),dy=Hc(),py=Br(),hy=Zt(),fy=pa(),my=Re(),by=en(),jc=Object.getOwnPropertyDescriptor;Gc.f=ly?jc:function(e,t){if(e=hy(e),t=fy(t),by)try{return jc(e,t)}catch(r){}if(my(e,t))return py(!cy(dy.f,e,t),e[t])}});var kn=m((l$,Yc)=>{"use strict";var gy=de(),vy=q(),Sy=/#|\.prototype\./,_r=function(i,e){var t=Ty[yy(i)];return t==Ey?!0:t==Iy?!1:vy(e)?gy(e):!!e},yy=_r.normalize=function(i){return String(i).replace(Sy,".").toLowerCase()},Ty=_r.data={},Iy=_r.NATIVE="N",Ey=_r.POLYFILL="P";Yc.exports=_r});var Nr=m((c$,Qc)=>{"use strict";var Wc=Pn(),xy=He(),Py=Lr(),wy=Wc(Wc.bind);Qc.exports=function(i,e){return xy(i),e===void 0?i:Py?wy(i,e):function(){return i.apply(e,arguments)}}});var ge=m((d$,Kc)=>{"use strict";var va=W(),ky=xn(),Ay=Pn(),Ry=q(),Ly=wn().f,$y=kn(),tr=la(),Cy=Nr(),rr=wt(),zc=Re(),Dy=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 ky(i,this,arguments)};return e.prototype=i.prototype,e};Kc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?va:a?va[t]:(va[t]||{}).prototype,o=r?tr:tr[t]||rr(tr,t,{})[t],l=o.prototype,u,c,d,p,f,h,b,v,S;for(p in e)u=$y(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&zc(n,p),h=o[p],c&&(i.dontCallGetSet?(S=Ly(n,p),b=S&&S.value):b=n[p]),f=c&&b?b:e[p],!(c&&typeof h==typeof f)&&(i.bind&&c?v=Cy(f,va):i.wrap&&c?v=Dy(f):s&&Ry(f)?v=Ay(f):v=f,(i.sham||f&&f.sham||h&&h.sham)&&rr(v,"sham",!0),rr(o,p,v),s&&(d=t+"Prototype",zc(tr,d)||rr(tr,d,{}),rr(tr[d],p,f),i.real&&l&&(u||!l[p])&&rr(l,p,f)))}});var Zc=m((p$,Xc)=>{"use strict";var An=Ve(),My=Re(),Jc=Function.prototype,Oy=An&&Object.getOwnPropertyDescriptor,Rn=My(Jc,"name"),By=Rn&&function(){}.name==="something",Vy=Rn&&(!An||An&&Oy(Jc,"name").configurable);Xc.exports={EXISTS:Rn,PROPER:By,CONFIGURABLE:Vy}});var td=m((h$,ed)=>{"use strict";var _y=Math.ceil,Ny=Math.floor;ed.exports=Math.trunc||function(e){var t=+e;return(t>0?Ny:_y)(t)}});var Sa=m((f$,rd)=>{"use strict";var Fy=td();rd.exports=function(i){var e=+i;return e!==e||e===0?0:Fy(e)}});var ad=m((m$,id)=>{"use strict";var qy=Sa(),Uy=Math.max,Hy=Math.min;id.exports=function(i,e){var t=qy(i);return t<0?Uy(t+e,0):Hy(t,e)}});var nd=m((b$,sd)=>{"use strict";var jy=Sa(),Gy=Math.min;sd.exports=function(i){return i>0?Gy(jy(i),9007199254740991):0}});var ya=m((g$,od)=>{"use strict";var Yy=nd();od.exports=function(i){return Yy(i.length)}});var cd=m((v$,ld)=>{"use strict";var Wy=Zt(),Qy=ad(),zy=ya(),ud=function(i){return function(e,t,r){var a=Wy(e),s=zy(a),n=Qy(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}};ld.exports={includes:ud(!0),indexOf:ud(!1)}});var hd=m((S$,pd)=>{"use strict";var Ky=re(),Ln=Re(),Jy=Zt(),Xy=cd().indexOf,Zy=ma(),dd=Ky([].push);pd.exports=function(i,e){var t=Jy(i),r=0,a=[],s;for(s in t)!Ln(Zy,s)&&Ln(t,s)&&dd(a,s);for(;e.length>r;)Ln(t,s=e[r++])&&(~Xy(a,s)||dd(a,s));return a}});var $n=m((y$,fd)=>{"use strict";fd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var bd=m((T$,md)=>{"use strict";var eT=hd(),tT=$n();md.exports=Object.keys||function(e){return eT(e,tT)}});var vd=m(gd=>{"use strict";var rT=Ve(),iT=tn(),aT=Pt(),sT=we(),nT=Zt(),oT=bd();gd.f=rT&&!iT?Object.defineProperties:function(e,t){sT(e);for(var r=nT(t),a=oT(t),s=a.length,n=0,o;s>n;)aT.f(e,o=a[n++],r[o]);return e}});var Cn=m((E$,Sd)=>{"use strict";var uT=Ue();Sd.exports=uT("document","documentElement")});var Bn=m((x$,wd)=>{"use strict";var lT=we(),cT=vd(),yd=$n(),dT=ma(),pT=Cn(),hT=oa(),fT=fa(),Td=">",Id="<",Mn="prototype",On="script",xd=fT("IE_PROTO"),Dn=function(){},Pd=function(i){return Id+On+Td+i+Id+"/"+On+Td},Ed=function(i){i.write(Pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},mT=function(){var i=hT("iframe"),e="java"+On+":",t;return i.style.display="none",pT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Pd("document.F=Object")),t.close(),t.F},Ta,Ia=function(){try{Ta=new ActiveXObject("htmlfile")}catch(e){}Ia=typeof document!="undefined"?document.domain&&Ta?Ed(Ta):mT():Ed(Ta);for(var i=yd.length;i--;)delete Ia[Mn][yd[i]];return Ia()};dT[xd]=!0;wd.exports=Object.create||function(e,t){var r;return e!==null?(Dn[Mn]=lT(e),r=new Dn,Dn[Mn]=null,r[xd]=e):r=Ia(),t===void 0?r:cT.f(r,t)}});var Ad=m((P$,kd)=>{"use strict";var bT=de();kd.exports=!bT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var _n=m((w$,Ld)=>{"use strict";var gT=Re(),vT=q(),ST=Or(),yT=fa(),TT=Ad(),Rd=yT("IE_PROTO"),Vn=Object,IT=Vn.prototype;Ld.exports=TT?Vn.getPrototypeOf:function(i){var e=ST(i);if(gT(e,Rd))return e[Rd];var t=e.constructor;return vT(t)&&e instanceof t?t.prototype:e instanceof Vn?IT:null}});var ir=m((k$,$d)=>{"use strict";var ET=wt();$d.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:ET(i,e,t),i}});var Un=m((A$,Md)=>{"use strict";var xT=de(),PT=q(),wT=Be(),kT=Bn(),Cd=_n(),AT=ir(),RT=K(),LT=Ae(),qn=RT("iterator"),Dd=!1,je,Nn,Fn;[].keys&&(Fn=[].keys(),"next"in Fn?(Nn=Cd(Cd(Fn)),Nn!==Object.prototype&&(je=Nn)):Dd=!0);var $T=!wT(je)||xT(function(){var i={};return je[qn].call(i)!==i});$T?je={}:LT&&(je=kT(je));PT(je[qn])||AT(je,qn,function(){return this});Md.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:Dd}});var Ea=m((R$,Bd)=>{"use strict";var CT=K(),DT=CT("toStringTag"),Od={};Od[DT]="z";Bd.exports=String(Od)==="[object z]"});var ar=m((L$,Vd)=>{"use strict";var MT=Ea(),OT=q(),xa=Jt(),BT=K(),VT=BT("toStringTag"),_T=Object,NT=xa(function(){return arguments}())=="Arguments",FT=function(i,e){try{return i[e]}catch(t){}};Vd.exports=MT?xa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=FT(e=_T(i),VT))=="string"?t:NT?xa(e):(r=xa(e))=="Object"&&OT(e.callee)?"Arguments":r}});var Nd=m(($$,_d)=>{"use strict";var qT=Ea(),UT=ar();_d.exports=qT?{}.toString:function(){return"[object "+UT(this)+"]"}});var Pa=m((C$,qd)=>{"use strict";var HT=Ea(),jT=Pt().f,GT=wt(),YT=Re(),WT=Nd(),QT=K(),Fd=QT("toStringTag");qd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;YT(a,Fd)||jT(a,Fd,{configurable:!0,value:e}),r&&!HT&&GT(a,"toString",WT)}}});var Hd=m((D$,Ud)=>{"use strict";var zT=Un().IteratorPrototype,KT=Bn(),JT=Br(),XT=Pa(),ZT=xt(),eI=function(){return this};Ud.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=KT(zT,{next:JT(+!r,t)}),XT(i,a,!1,!0),ZT[a]=eI,i}});var Gd=m((M$,jd)=>{"use strict";var tI=re(),rI=He();jd.exports=function(i,e,t){try{return tI(rI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var Wd=m((O$,Yd)=>{"use strict";var iI=q(),aI=String,sI=TypeError;Yd.exports=function(i){if(typeof i=="object"||iI(i))return i;throw sI("Can't set "+aI(i)+" as a prototype")}});var Hn=m((B$,Qd)=>{"use strict";var nI=Gd(),oI=we(),uI=Wd();Qd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=nI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return oI(a),uI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var sp=m((V$,ap)=>{"use strict";var lI=ge(),cI=ie(),wa=Ae(),rp=Zc(),dI=q(),pI=Hd(),zd=_n(),Kd=Hn(),hI=Pa(),fI=wt(),jn=ir(),mI=K(),Jd=xt(),ip=Un(),bI=rp.PROPER,gI=rp.CONFIGURABLE,Xd=ip.IteratorPrototype,ka=ip.BUGGY_SAFARI_ITERATORS,Fr=mI("iterator"),Zd="keys",qr="values",ep="entries",tp=function(){return this};ap.exports=function(i,e,t,r,a,s,n){pI(t,e,r);var o=function(S){if(S===a&&p)return p;if(!ka&&S in c)return c[S];switch(S){case Zd:return function(){return new t(this,S)};case qr:return function(){return new t(this,S)};case ep:return function(){return new t(this,S)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Fr]||c["@@iterator"]||a&&c[a],p=!ka&&d||o(a),f=e=="Array"&&c.entries||d,h,b,v;if(f&&(h=zd(f.call(new i)),h!==Object.prototype&&h.next&&(!wa&&zd(h)!==Xd&&(Kd?Kd(h,Xd):dI(h[Fr])||jn(h,Fr,tp)),hI(h,l,!0,!0),wa&&(Jd[l]=tp))),bI&&a==qr&&d&&d.name!==qr&&(!wa&&gI?fI(c,"name",qr):(u=!0,p=function(){return cI(d,this)})),a)if(b={values:o(qr),keys:s?p:o(Zd),entries:o(ep)},n)for(v in b)(ka||u||!(v in c))&&jn(c,v,b[v]);else lI({target:e,proto:!0,forced:ka||u},b);return(!wa||n)&&c[Fr]!==p&&jn(c,Fr,p,{name:a}),Jd[e]=p,b}});var op=m((_$,np)=>{"use strict";np.exports=function(i,e){return{value:i,done:e}}});var Yn=m((N$,pp)=>{"use strict";var vI=Zt(),Gn=Ks(),up=xt(),cp=En(),SI=Pt().f,yI=sp(),Aa=op(),TI=Ae(),II=Ve(),dp="Array Iterator",EI=cp.set,xI=cp.getterFor(dp);pp.exports=yI(Array,"Array",function(i,e){EI(this,{type:dp,target:vI(i),index:0,kind:e})},function(){var i=xI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Aa(void 0,!0)):t=="keys"?Aa(r,!1):t=="values"?Aa(e[r],!1):Aa([r,e[r]],!1)},"values");var lp=up.Arguments=up.Array;Gn("keys");Gn("values");Gn("entries");if(!TI&&II&&lp.name!=="values")try{SI(lp,"name",{value:"values"})}catch(i){}});var fp=m((F$,hp)=>{"use strict";var PI=K(),wI=xt(),kI=PI("iterator"),AI=Array.prototype;hp.exports=function(i){return i!==void 0&&(wI.Array===i||AI[kI]===i)}});var Wn=m((q$,bp)=>{"use strict";var RI=ar(),mp=Mr(),LI=Xt(),$I=xt(),CI=K(),DI=CI("iterator");bp.exports=function(i){if(!LI(i))return mp(i,DI)||mp(i,"@@iterator")||$I[RI(i)]}});var vp=m((U$,gp)=>{"use strict";var MI=ie(),OI=He(),BI=we(),VI=Dr(),_I=Wn(),NI=TypeError;gp.exports=function(i,e){var t=arguments.length<2?_I(i):e;if(OI(t))return BI(MI(t,i));throw NI(VI(i)+" is not iterable")}});var Tp=m((H$,yp)=>{"use strict";var FI=ie(),Sp=we(),qI=Mr();yp.exports=function(i,e,t){var r,a;Sp(i);try{if(r=qI(i,"return"),!r){if(e==="throw")throw t;return t}r=FI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Sp(r),t}});var La=m((j$,Pp)=>{"use strict";var UI=Nr(),HI=ie(),jI=we(),GI=Dr(),YI=fp(),WI=ya(),Ip=$r(),QI=vp(),zI=Wn(),Ep=Tp(),KI=TypeError,Ra=function(i,e){this.stopped=i,this.result=e},xp=Ra.prototype;Pp.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=UI(e,r),u,c,d,p,f,h,b,v=function(g){return u&&Ep(u,"normal",g),new Ra(!0,g)},S=function(g){return a?(jI(g),o?l(g[0],g[1],v):l(g[0],g[1])):o?l(g,v):l(g)};if(s)u=i.iterator;else if(n)u=i;else{if(c=zI(i),!c)throw KI(GI(i)+" is not iterable");if(YI(c)){for(d=0,p=WI(i);p>d;d++)if(f=S(i[d]),f&&Ip(xp,f))return f;return new Ra(!1)}u=QI(i,c)}for(h=s?i.next:u.next;!(b=HI(h,u)).done;){try{f=S(b.value)}catch(g){Ep(u,"throw",g)}if(typeof f=="object"&&f&&Ip(xp,f))return f}return new Ra(!1)}});var kp=m((G$,wp)=>{"use strict";var JI=pa(),XI=Pt(),ZI=Br();wp.exports=function(i,e,t){var r=JI(e);r in i?XI.f(i,r,ZI(0,t)):i[r]=t}});var Ap=m(()=>{"use strict";var eE=ge(),tE=La(),rE=kp();eE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return tE(e,function(r,a){rE(t,r,a)},{AS_ENTRIES:!0}),t}})});var Lp=m((Q$,Rp)=>{"use strict";Yn();Ap();var iE=la();Rp.exports=iE.Object.fromEntries});var Cp=m((z$,$p)=>{"use strict";$p.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 Op=m(()=>{"use strict";Yn();var aE=Cp(),sE=W(),nE=ar(),oE=wt(),Dp=xt(),uE=K(),Mp=uE("toStringTag");for($a in aE)Qn=sE[$a],Ca=Qn&&Qn.prototype,Ca&&nE(Ca)!==Mp&&oE(Ca,Mp,$a),Dp[$a]=Dp.Array;var Qn,Ca,$a});var Vp=m((X$,Bp)=>{"use strict";var lE=Lp();Op();Bp.exports=lE});var Da=m((Z$,_p)=>{"use strict";var cE=Vp();_p.exports=cE});var Np=m(()=>{"use strict"});var Ur=m((rC,Fp)=>{"use strict";var dE=Jt();Fp.exports=typeof process!="undefined"&&dE(process)=="process"});var Up=m((iC,qp)=>{"use strict";var pE=Pt();qp.exports=function(i,e,t){return pE.f(i,e,t)}});var Gp=m((aC,jp)=>{"use strict";var hE=Ue(),fE=Up(),mE=K(),bE=Ve(),Hp=mE("species");jp.exports=function(i){var e=hE(i);bE&&e&&!e[Hp]&&fE(e,Hp,{configurable:!0,get:function(){return this}})}});var Wp=m((sC,Yp)=>{"use strict";var gE=$r(),vE=TypeError;Yp.exports=function(i,e){if(gE(e,i))return i;throw vE("Incorrect invocation")}});var Kn=m((nC,Qp)=>{"use strict";var SE=re(),yE=q(),zn=da(),TE=SE(Function.toString);yE(zn.inspectSource)||(zn.inspectSource=function(i){return TE(i)});Qp.exports=zn.inspectSource});var eh=m((oC,Zp)=>{"use strict";var IE=re(),EE=de(),zp=q(),xE=ar(),PE=Ue(),wE=Kn(),Kp=function(){},kE=[],Jp=PE("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,AE=IE(Jn.exec),RE=!Jn.exec(Kp),Hr=function(e){if(!zp(e))return!1;try{return Jp(Kp,kE,e),!0}catch(t){return!1}},Xp=function(e){if(!zp(e))return!1;switch(xE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RE||!!AE(Jn,wE(e))}catch(t){return!0}};Xp.sham=!0;Zp.exports=!Jp||EE(function(){var i;return Hr(Hr.call)||!Hr(Object)||!Hr(function(){i=!0})||i})?Xp:Hr});var rh=m((uC,th)=>{"use strict";var LE=eh(),$E=Dr(),CE=TypeError;th.exports=function(i){if(LE(i))return i;throw CE($E(i)+" is not a constructor")}});var Xn=m((lC,ah)=>{"use strict";var ih=we(),DE=rh(),ME=Xt(),OE=K(),BE=OE("species");ah.exports=function(i,e){var t=ih(i).constructor,r;return t===void 0||ME(r=ih(t)[BE])?e:DE(r)}});var nh=m((cC,sh)=>{"use strict";var VE=re();sh.exports=VE([].slice)});var uh=m((dC,oh)=>{"use strict";var _E=TypeError;oh.exports=function(i,e){if(i<e)throw _E("Not enough arguments");return i}});var Zn=m((pC,lh)=>{"use strict";var NE=Cr();lh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(NE)});var uo=m((hC,vh)=>{"use strict";var pe=W(),FE=xn(),qE=Nr(),ch=q(),UE=Re(),gh=de(),dh=Cn(),HE=nh(),ph=oa(),jE=uh(),GE=Zn(),YE=Ur(),so=pe.setImmediate,no=pe.clearImmediate,WE=pe.process,eo=pe.Dispatch,QE=pe.Function,hh=pe.MessageChannel,zE=pe.String,to=0,jr={},fh="onreadystatechange",Gr,At,ro,io;gh(function(){Gr=pe.location});var oo=function(i){if(UE(jr,i)){var e=jr[i];delete jr[i],e()}},ao=function(i){return function(){oo(i)}},mh=function(i){oo(i.data)},bh=function(i){pe.postMessage(zE(i),Gr.protocol+"//"+Gr.host)};(!so||!no)&&(so=function(e){jE(arguments.length,1);var t=ch(e)?e:QE(e),r=HE(arguments,1);return jr[++to]=function(){FE(t,void 0,r)},At(to),to},no=function(e){delete jr[e]},YE?At=function(i){WE.nextTick(ao(i))}:eo&&eo.now?At=function(i){eo.now(ao(i))}:hh&&!GE?(ro=new hh,io=ro.port2,ro.port1.onmessage=mh,At=qE(io.postMessage,io)):pe.addEventListener&&ch(pe.postMessage)&&!pe.importScripts&&Gr&&Gr.protocol!=="file:"&&!gh(bh)?(At=bh,pe.addEventListener("message",mh,!1)):fh in ph("script")?At=function(i){dh.appendChild(ph("script"))[fh]=function(){dh.removeChild(this),oo(i)}}:At=function(i){setTimeout(ao(i),0)});vh.exports={set:so,clear:no}});var lo=m((fC,yh)=>{"use strict";var Sh=function(){this.head=null,this.tail=null};Sh.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}}};yh.exports=Sh});var Ih=m((mC,Th)=>{"use strict";var KE=Cr();Th.exports=/ipad|iphone|ipod/i.test(KE)&&typeof Pebble!="undefined"});var xh=m((bC,Eh)=>{"use strict";var JE=Cr();Eh.exports=/web0s(?!.*chrome)/i.test(JE)});var Ch=m((gC,$h)=>{"use strict";var Rt=W(),Ph=Nr(),XE=wn().f,co=uo().set,ZE=lo(),ex=Zn(),tx=Ih(),rx=xh(),po=Ur(),wh=Rt.MutationObserver||Rt.WebKitMutationObserver,kh=Rt.document,Ah=Rt.process,Ma=Rt.Promise,Rh=XE(Rt,"queueMicrotask"),mo=Rh&&Rh.value,sr,ho,fo,Oa,Lh;mo||(Yr=new ZE,Wr=function(){var i,e;for(po&&(i=Ah.domain)&&i.exit();e=Yr.get();)try{e()}catch(t){throw Yr.head&&sr(),t}i&&i.enter()},!ex&&!po&&!rx&&wh&&kh?(ho=!0,fo=kh.createTextNode(""),new wh(Wr).observe(fo,{characterData:!0}),sr=function(){fo.data=ho=!ho}):!tx&&Ma&&Ma.resolve?(Oa=Ma.resolve(void 0),Oa.constructor=Ma,Lh=Ph(Oa.then,Oa),sr=function(){Lh(Wr)}):po?sr=function(){Ah.nextTick(Wr)}:(co=Ph(co,Rt),sr=function(){co(Wr)}),mo=function(i){Yr.head||sr(),Yr.add(i)});var Yr,Wr;$h.exports=mo});var Mh=m((vC,Dh)=>{"use strict";Dh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Ba=m((SC,Oh)=>{"use strict";Oh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Lt=m((yC,Bh)=>{"use strict";var ix=W();Bh.exports=ix.Promise});var bo=m((TC,Vh)=>{"use strict";Vh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Nh=m((IC,_h)=>{"use strict";var ax=bo(),sx=Ur();_h.exports=!ax&&!sx&&typeof window=="object"&&typeof document=="object"});var nr=m((EC,Uh)=>{"use strict";var nx=W(),Qr=Lt(),ox=q(),ux=kn(),lx=Kn(),cx=K(),dx=Nh(),px=bo(),hx=Ae(),go=nn(),Fh=Qr&&Qr.prototype,fx=cx("species"),vo=!1,qh=ox(nx.PromiseRejectionEvent),mx=ux("Promise",function(){var i=lx(Qr),e=i!==String(Qr);if(!e&&go===66||hx&&!(Fh.catch&&Fh.finally))return!0;if(!go||go<51||!/native code/.test(i)){var t=new Qr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[fx]=r,vo=t.then(function(){})instanceof r,!vo)return!0}return!e&&(dx||px)&&!qh});Uh.exports={CONSTRUCTOR:mx,REJECTION_EVENT:qh,SUBCLASSING:vo}});var or=m((xC,jh)=>{"use strict";var Hh=He(),bx=TypeError,gx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw bx("Bad Promise constructor");e=r,t=a}),this.resolve=Hh(e),this.reject=Hh(t)};jh.exports.f=function(i){return new gx(i)}});var cf=m(()=>{"use strict";var vx=ge(),Sx=Ae(),Fa=Ur(),st=W(),dr=ie(),Gh=ir(),Yh=Hn(),yx=Pa(),Tx=Gp(),Ix=He(),Na=q(),Ex=Be(),xx=Wp(),Px=Xn(),Jh=uo().set,Eo=Ch(),wx=Mh(),kx=Ba(),Ax=lo(),Xh=En(),qa=Lt(),xo=nr(),Zh=or(),Ua="Promise",ef=xo.CONSTRUCTOR,Rx=xo.REJECTION_EVENT,Lx=xo.SUBCLASSING,So=Xh.getterFor(Ua),$x=Xh.set,ur=qa&&qa.prototype,$t=qa,Va=ur,tf=st.TypeError,yo=st.document,Po=st.process,To=Zh.f,Cx=To,Dx=!!(yo&&yo.createEvent&&st.dispatchEvent),rf="unhandledrejection",Mx="rejectionhandled",Wh=0,af=1,Ox=2,wo=1,sf=2,_a,Qh,Bx,zh,nf=function(i){var e;return Ex(i)&&Na(e=i.then)?e:!1},of=function(i,e){var t=e.value,r=e.state==af,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===sf&&_x(e),e.rejection=wo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(tf("Promise-chain cycle")):(u=nf(l))?dr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},uf=function(i,e){i.notified||(i.notified=!0,Eo(function(){for(var t=i.reactions,r;r=t.get();)of(r,i);i.notified=!1,e&&!i.rejection&&Vx(i)}))},lf=function(i,e,t){var r,a;Dx?(r=yo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),st.dispatchEvent(r)):r={promise:e,reason:t},!Rx&&(a=st["on"+i])?a(r):i===rf&&wx("Unhandled promise rejection",t)},Vx=function(i){dr(Jh,st,function(){var e=i.facade,t=i.value,r=Kh(i),a;if(r&&(a=kx(function(){Fa?Po.emit("unhandledRejection",t,e):lf(rf,e,t)}),i.rejection=Fa||Kh(i)?sf:wo,a.error))throw a.value})},Kh=function(i){return i.rejection!==wo&&!i.parent},_x=function(i){dr(Jh,st,function(){var e=i.facade;Fa?Po.emit("rejectionHandled",e):lf(Mx,e,i.value)})},lr=function(i,e,t){return function(r){i(e,r,t)}},cr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Ox,uf(i,!0))},Io=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw tf("Promise can't be resolved itself");var r=nf(e);r?Eo(function(){var a={done:!1};try{dr(r,e,lr(Io,a,i),lr(cr,a,i))}catch(s){cr(a,s,i)}}):(i.value=e,i.state=af,uf(i,!1))}catch(a){cr({done:!1},a,i)}}};if(ef&&($t=function(e){xx(this,Va),Ix(e),dr(_a,this);var t=So(this);try{e(lr(Io,t),lr(cr,t))}catch(r){cr(t,r)}},Va=$t.prototype,_a=function(e){$x(this,{type:Ua,done:!1,notified:!1,parent:!1,reactions:new Ax,rejection:!1,state:Wh,value:void 0})},_a.prototype=Gh(Va,"then",function(e,t){var r=So(this),a=To(Px(this,$t));return r.parent=!0,a.ok=Na(e)?e:!0,a.fail=Na(t)&&t,a.domain=Fa?Po.domain:void 0,r.state==Wh?r.reactions.add(a):Eo(function(){of(a,r)}),a.promise}),Qh=function(){var i=new _a,e=So(i);this.promise=i,this.resolve=lr(Io,e),this.reject=lr(cr,e)},Zh.f=To=function(i){return i===$t||i===Bx?new Qh(i):Cx(i)},!Sx&&Na(qa)&&ur!==Object.prototype)){zh=ur.then,Lx||Gh(ur,"then",function(e,t){var r=this;return new $t(function(a,s){dr(zh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch(i){}Yh&&Yh(ur,Va)}vx({global:!0,constructor:!0,wrap:!0,forced:ef},{Promise:$t});yx($t,Ua,!1,!0);Tx(Ua)});var mf=m((kC,ff)=>{"use strict";var Nx=K(),pf=Nx("iterator"),hf=!1;try{df=0,ko={next:function(){return{done:!!df++}},return:function(){hf=!0}},ko[pf]=function(){return this},Array.from(ko,function(){throw 2})}catch(i){}var df,ko;ff.exports=function(i,e){if(!e&&!hf)return!1;var t=!1;try{var r={};r[pf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Ao=m((AC,bf)=>{"use strict";var Fx=Lt(),qx=mf(),Ux=nr().CONSTRUCTOR;bf.exports=Ux||!qx(function(i){Fx.all(i).then(void 0,function(){})})});var gf=m(()=>{"use strict";var Hx=ge(),jx=ie(),Gx=He(),Yx=or(),Wx=Ba(),Qx=La(),zx=Ao();Hx({target:"Promise",stat:!0,forced:zx},{all:function(e){var t=this,r=Yx.f(t),a=r.resolve,s=r.reject,n=Wx(function(){var o=Gx(t.resolve),l=[],u=0,c=1;Qx(e,function(d){var p=u++,f=!1;c++,jx(o,t,d).then(function(h){f||(f=!0,l[p]=h,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var Sf=m(()=>{"use strict";var Kx=ge(),Jx=Ae(),Xx=nr().CONSTRUCTOR,Lo=Lt(),Zx=Ue(),eP=q(),tP=ir(),vf=Lo&&Lo.prototype;Kx({target:"Promise",proto:!0,forced:Xx,real:!0},{catch:function(i){return this.then(void 0,i)}});!Jx&&eP(Lo)&&(Ro=Zx("Promise").prototype.catch,vf.catch!==Ro&&tP(vf,"catch",Ro,{unsafe:!0}));var Ro});var yf=m(()=>{"use strict";var rP=ge(),iP=ie(),aP=He(),sP=or(),nP=Ba(),oP=La(),uP=Ao();rP({target:"Promise",stat:!0,forced:uP},{race:function(e){var t=this,r=sP.f(t),a=r.reject,s=nP(function(){var n=aP(t.resolve);oP(e,function(o){iP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Tf=m(()=>{"use strict";var lP=ge(),cP=ie(),dP=or(),pP=nr().CONSTRUCTOR;lP({target:"Promise",stat:!0,forced:pP},{reject:function(e){var t=dP.f(this);return cP(t.reject,void 0,e),t.promise}})});var $o=m((VC,If)=>{"use strict";var hP=we(),fP=Be(),mP=or();If.exports=function(i,e){if(hP(i),fP(e)&&e.constructor===i)return e;var t=mP.f(i),r=t.resolve;return r(e),t.promise}});var Pf=m(()=>{"use strict";var bP=ge(),gP=Ue(),Ef=Ae(),vP=Lt(),xf=nr().CONSTRUCTOR,SP=$o(),yP=gP("Promise"),TP=Ef&&!xf;bP({target:"Promise",stat:!0,forced:Ef||xf},{resolve:function(e){return SP(TP&&this===yP?vP:this,e)}})});var wf=m(()=>{"use strict";cf();gf();Sf();yf();Tf();Pf()});var Lf=m(()=>{"use strict";var IP=ge(),EP=Ae(),Ha=Lt(),xP=de(),Af=Ue(),Rf=q(),PP=Xn(),kf=$o(),wP=ir(),Do=Ha&&Ha.prototype,kP=!!Ha&&xP(function(){Do.finally.call({then:function(){}},function(){})});IP({target:"Promise",proto:!0,real:!0,forced:kP},{finally:function(i){var e=PP(this,Af("Promise")),t=Rf(i);return this.then(t?function(r){return kf(e,i()).then(function(){return r})}:i,t?function(r){return kf(e,i()).then(function(){throw r})}:i)}});!EP&&Rf(Ha)&&(Co=Af("Promise").prototype.finally,Do.finally!==Co&&wP(Do,"finally",Co,{unsafe:!0}));var Co});var ja=m((jC,$f)=>{"use strict";var AP=Ue();$f.exports=AP});var Df=m((GC,Cf)=>{"use strict";Np();wf();Lf();var RP=ja();Cf.exports=RP("Promise","finally")});var Of=m((YC,Mf)=>{"use strict";var LP=Df();Mf.exports=LP});var Ga=m((WC,Bf)=>{"use strict";var $P=Of();Bf.exports=$P});var nm=m(()=>{"use strict";var iw=ge(),aw=Or(),sw=ya(),nw=Sa(),ow=Ks();iw({target:"Array",proto:!0},{at:function(e){var t=aw(this),r=sw(t),a=nw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});ow("at")});var um=m((rM,om)=>{"use strict";nm();var uw=ja();om.exports=uw("Array","at")});var cm=m((iM,lm)=>{"use strict";var lw=um();lm.exports=lw});var Qa=m((aM,dm)=>{"use strict";var cw=cm();dm.exports=cw});var Hm=m(()=>{"use strict"});var jm=m(()=>{"use strict"});var Ym=m((jB,Gm)=>{"use strict";var mk=Be(),bk=Jt(),gk=K(),vk=gk("match");Gm.exports=function(i){var e;return mk(i)&&((e=i[vk])!==void 0?!!e:bk(i)=="RegExp")}});var Qm=m((GB,Wm)=>{"use strict";var Sk=ar(),yk=String;Wm.exports=function(i){if(Sk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return yk(i)}});var Km=m((YB,zm)=>{"use strict";var Tk=we();zm.exports=function(){var i=Tk(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 Zm=m((WB,Xm)=>{"use strict";var Ik=ie(),Ek=Re(),xk=$r(),Pk=Km(),Jm=RegExp.prototype;Xm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Jm)&&!Ek(i,"flags")&&xk(Jm,i)?Ik(Pk,i):e}});var tb=m((QB,eb)=>{"use strict";var nu=re(),wk=Or(),kk=Math.floor,au=nu("".charAt),Ak=nu("".replace),su=nu("".slice),Rk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Lk=/\$([$&'`]|\d{1,2})/g;eb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=Lk;return a!==void 0&&(a=wk(a),l=Rk),Ak(s,l,function(u,c){var d;switch(au(c,0)){case"$":return"$";case"&":return i;case"`":return su(e,0,t);case"'":return su(e,n);case"<":d=a[su(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var f=kk(p/10);return f===0?u:f<=o?r[f-1]===void 0?au(c,1):r[f-1]+au(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var nb=m(()=>{"use strict";var $k=ge(),Ck=ie(),ou=re(),rb=sa(),Dk=q(),Mk=Xt(),Ok=Ym(),vr=Qm(),Bk=Mr(),Vk=Zm(),_k=tb(),Nk=K(),Fk=Ae(),qk=Nk("replace"),Uk=TypeError,sb=ou("".indexOf),Hk=ou("".replace),ib=ou("".slice),jk=Math.max,ab=function(i,e,t){return t>i.length?-1:e===""?t:sb(i,e,t)};$k({target:"String",proto:!0},{replaceAll:function(e,t){var r=rb(this),a,s,n,o,l,u,c,d,p,f=0,h=0,b="";if(!Mk(e)){if(a=Ok(e),a&&(s=vr(rb(Vk(e))),!~sb(s,"g")))throw Uk("`.replaceAll` does not allow non-global regexes");if(n=Bk(e,qk),n)return Ck(n,e,r,t);if(Fk&&a)return Hk(vr(r),e,t)}for(o=vr(r),l=vr(e),u=Dk(t),u||(t=vr(t)),c=l.length,d=jk(1,c),f=ab(o,l,0);f!==-1;)p=u?vr(t(l,f,o)):_k(l,o,f,[],void 0,t),b+=ib(o,h,f)+p,h=f+c,f=ab(o,l,f+d);return h<o.length&&(b+=ib(o,h)),b}})});var ub=m((JB,ob)=>{"use strict";Hm();jm();nb();var Gk=ja();ob.exports=Gk("String","replaceAll")});var cb=m((XB,lb)=>{"use strict";var Yk=ub();lb.exports=Yk});var pb=m((ZB,db)=>{"use strict";var Wk=cb();db.exports=Wk});var rl="__VERSION__";var ce=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ce||{}),Et=(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))(Et||{});var ra=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ra||{}),js=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(js||{});var Gs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Gs||{});import{assertNever as ul,assertNonNullable as hv,isNonNullable as ia,ValueSubject as Ys,Subject as fv,Subscription as mv,merge as bv,observableFrom as gv,fromEvent as al,map as sl,tap as nl,filterChanged as vv,isNullable as Ws,ErrorCategory as ol}from"@vkontakte/videoplayer-shared";var il=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 aa=class{constructor(e){this.connection$=new Ys(void 0);this.castState$=new Ys("NOT_AVAILABLE");this.errorEvent$=new fv;this.realCastState$=new Ys("NOT_AVAILABLE");this.subscription=new mv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=ia((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||il("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ol.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ws(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ws(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(al(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return ul(a.sessionState)}})).add(bv(al(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(nl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),sl(a=>a.castState)),gv([r.getCastState()])).pipe(vv(),sl(Sv),nl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=ia(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();hv(l);let u=l.getCastDevice(),c=(o=l.getMediaSession())==null?void 0:o.media.contentId;(Ws(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?ia(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ol.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Sv=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 ul(i)}};var Rg=Oe(Da(),1);var Yf=Oe(Ga(),1);import{assertNever as Vf}from"@vkontakte/videoplayer-shared";var J=(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:Vf(t)}return i},Mo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Vf(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as CP,Subject as Ya,merge as _f}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ya;this.transitionEnded$=new Ya;this.transitionUpdated$=new Ya;this.forceChanged$=new Ya;this.stateChangeStarted$=_f(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_f(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||CP(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 DP}from"@vkontakte/videoplayer-shared";var Nf=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 DP(i)}};import{assertNever as pr,assertNonNullable as Ct,debounce as Ff,ErrorCategory as qf,fromEvent as Dt,isNonNullable as Uf,map as Hf,merge as jf,observableFrom as MP,Subject as OP,Subscription as Oo,timeout as BP,getHighestQuality as VP}from"@vkontakte/videoplayer-shared";var _P=5,NP=5,FP=500,Gf=7e3,zr=class{constructor(e){this.subscription=new Oo;this.loadMediaTimeoutSubscription=new Oo;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==null?void 0:a.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:pr(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:pr(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:pr(e)}break}default:pr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Nf(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 Oo;this.subscription.add(e),this.subscription.add(jf(this.videoState.stateChangeStarted$.pipe(Hf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Hf(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 OP;e.add(a.pipe(Ff(FP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Dt(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)>_P)&&a.next(o),s=o})),e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Dt(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<NP&&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:pr(n)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=jf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,MP(["init"])).pipe(Ff(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var u;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Ct(c);let d=VP(Object.keys(c));Ct(d);let p=c[d];Ct(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ct(c),r=c.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let c=t[e];Ct(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ct(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ct(c),r=J(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:qf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return pr(e)}let n=new chrome.cast.media.MediaInfo((u=this.params.meta.videoId)!=null?u:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return Uf(o)&&(n.metadata.title=o),Uf(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(BP(Gf).subscribe(()=>s(`timeout(${Gf})`)))});(0,Yf.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:qf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Kr=i=>{i.removeAttribute("src"),i.load()};var Wf=i=>{try{i.pause(),i.playbackRate=0,Kr(i),i.remove()}catch(e){console.error(e)}};var Bo=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)}},Vo=window.WeakMap?new WeakMap:new Bo,ae=i=>{let e=i.querySelector("video"),t=!!e;return e?Kr(e):(e=document.createElement("video"),i.appendChild(e)),Vo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},se=i=>{let e=Vo.get(i);Vo.delete(i),e?Kr(i):Wf(i)};import{assertNonNullable as Jr,isNonNullable as Ne,isNullable as HP,fromEvent as hr,merge as Qf,observableFrom as zf,filterChanged as Kf,map as Xr,Subject as Jf,Subscription as jP,ValueSubject as GP,ErrorCategory as YP}from"@vkontakte/videoplayer-shared";import{isNonNullable as _o,isNullable as qP,Subscription as UP}from"@vkontakte/videoplayer-shared";var Wa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=qP(a),u=new UP;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)=>Wa(e,()=>i.loop,r=>{_o(r)&&(i.loop=r)},{onError:t}),ne=(i,e,t,r)=>Wa(e,()=>({muted:i.muted,volume:i.volume}),a=>{_o(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ve=(i,e,t,r)=>Wa(e,()=>i.playbackRate,a=>{_o(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),nt=Wa;var WP=i=>["__",i.language,i.label].join("|"),QP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},No=class i{constructor(){this.available$=new Jf;this.current$=new GP(void 0);this.error$=new Jf;this.subscription=new jP;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:YP.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(nt(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(Xr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(nt(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(Xr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(nt(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(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Jr(this.video);let{textTracks:e}=this.video;this.subscription.add(hr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Qf(hr(e,"addtrack"),hr(e,"removetrack"),zf(["init"])).pipe(Xr(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Kf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Qf(hr(e,"change"),zf(["init"])).pipe(Xr(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Xr(r=>r&&this.htmlTextTrackToITextTrack(r).id),Kf()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add(hr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var u,c,d,p,f;let l=(c=(u=o.target)==null?void 0:u.cues)!=null?c:null;l&&l.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(f=o.target)==null||f.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add(hr(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;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){Jr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,l;let{language:t,label:r}=e,a=e.id?e.id:WP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(l=this.internalTracks.get(a))==null?void 0:l.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){Jr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(HP(e)||!QP(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){Jr(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){Jr(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)}},Se=No;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 Xf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Fo=i=>{let e=Xf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Zf=i=>{let e=Xf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ye,map as ot,merge as tm,filterChanged as KP,isNonNullable as rm,Subject as JP,filter as im,mapTo as am,combine as XP,once as ZP,ErrorCategory as ew,ValueSubject as sm,getCurrentBrowser as tw,CurrentClientBrowser as rw}from"@vkontakte/videoplayer-shared";var zP=3,em=(i,e,t=zP)=>{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 oe=i=>{let e=I=>ye(i,I).pipe(am(void 0)),r=tm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>ye(i,I))).pipe(ot(I=>I.type==="ended"?i.readyState<2:i.readyState<3),KP()),a=tm(ye(i,"progress"),ye(i,"timeupdate")).pipe(ot(()=>em(i.buffered,i.currentTime))),n=tw().browser===rw.Safari?XP({play:e("play").pipe(ZP()),playing:e("playing")}).pipe(am(void 0)):e("playing"),o=ye(i,"volumechange").pipe(ot(()=>({muted:i.muted,volume:i.volume}))),l=ye(i,"ratechange").pipe(ot(()=>i.playbackRate)),u=ye(i,"error").pipe(im(()=>!!(i.error||i.played.length)),ot(()=>{var y;let I=i.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:ew.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(y=i.error)!=null?y:void 0}})),c=ye(i,"timeupdate").pipe(ot(()=>i.currentTime)),d=new JP,p=.3,f;c.subscribe(I=>{i.loop&&rm(f)&&rm(I)&&f>=i.duration-p&&I<=p&&d.next(f),f=I});let h=ye(i,"enterpictureinpicture"),b=ye(i,"leavepictureinpicture"),v=new sm(Zf(i));h.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));let S=new sm(Fo(i));return ye(i,"fullscreenchange").pipe(ot(()=>Fo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(im(()=>!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$:ye(i,"durationchange").pipe(ot(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:v,inFullscreen$:S}};import{VideoQuality as ut}from"@vkontakte/videoplayer-shared";var lt=i=>{switch(i){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};var Go=Oe(Qa(),1);import{isNonNullable as ct,isNullable as Uo,now as gm,isHigher as Ho,isHigherOrEqual as mm,isInvariantQuality as bm,isLower as jo,isLowerOrEqual as dw,videoSizeToQuality as pw,assertNotEmptyArray as hw}from"@vkontakte/videoplayer-shared";var qo=!1,We={},pm=i=>{qo=i},hm=()=>{We={}},fm=i=>{i(We)},Zr=(i,e)=>{var t;qo&&(We.meta=(t=We.meta)!=null?t:{},We.meta[i]=e)},Z=class{constructor(e){this.name=e}next(e){var r,a;if(!qo)return;We.series=(r=We.series)!=null?r:{};let t=(a=We.series[this.name])!=null?a:[];t.push([Date.now(),e]),We.series[this.name]=t}};var fw=new Z("best_bitrate"),mw=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,za=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},bw='Assertion "ABR Tracks is empty array" failed',gw=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var $,C,w,U,ee;hw(i,bw);let p=r.usePixelRatio&&($=window.devicePixelRatio)!=null?$:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},h=f&&pw(f),b=r.considerPlaybackRate&&ct(o)?o:1,v=i.filter(k=>!bm(k.quality)).sort((k,x)=>Ho(k.quality,x.quality)?-1:1),S=(C=(0,Go.default)(v,-1))==null?void 0:C.quality,g=(w=(0,Go.default)(v,0))==null?void 0:w.quality,I=Uo(a)||ct(a.min)&&ct(a.max)&&jo(a.max,a.min)||ct(a.min)&&g&&Ho(a.min,g)||ct(a.max)&&S&&jo(a.max,S),y=b*mw(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},R=v.filter(k=>(h?jo(k.quality,h):!0)?(ct(t)&&isFinite(t)&&ct(k.bitrate)?t-s>=k.bitrate*y:!0)?r.lazyQualitySwitch&&ct(r.minBufferToSwitchUp)&&l&&!bm(l.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Ho(k.quality,l.quality)?(E[k.quality]="Buffer",!1):!!c&&mm(k.quality,c)?(E[k.quality]="DroppedFramesLimit",!1):I||(Uo(a.max)||dw(k.quality,a.max))&&(Uo(a.min)||mm(k.quality,a.min))?!0:(E[k.quality]="FitsQualityLimits",!1):(E[k.quality]="FitsThroughput",!1):(E[k.quality]="FitsContainer",!1))[0];R&&R.bitrate&&fw.next(R.bitrate);let A=(U=R!=null?R:v[Math.ceil((v.length-1)/2)])!=null?U:i[0];A.quality!==((ee=u==null?void 0:u.last)==null?void 0:ee.quality)&&d({message:`
7
7
  [available tracks]
8
- ${i.map(B=>`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate} }`).join(`
8
+ ${i.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(s!=null?s:{}).map(([B,x])=>`${B}: ${x}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${x}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
- containerQualityLimit: ${A},
16
+ containerQualityLimit: ${h},
17
17
  throughput: ${t},
18
- reserve: ${a},
18
+ reserve: ${s},
19
19
  playbackRate: ${o},
20
- playbackRateFactor: ${w},
20
+ playbackRateFactor: ${b},
21
21
  forwardBufferHealth: ${n},
22
- bitrateFactor: ${G},
23
- minBufferToSwitchUp: ${s.minBufferToSwitchUp},
22
+ bitrateFactor: ${y},
23
+ minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
24
  droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${K},
26
- maxQualityLimit: ${r==null?void 0:r.max},
27
- minQualityLimit: ${r==null?void 0:r.min},
25
+ limitsAreInvalid: ${I},
26
+ maxQualityLimit: ${a==null?void 0:a.max},
27
+ minQualityLimit: ${a==null?void 0:a.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(J).map(([B,x])=>`${B}: ${x}`).join(`
30
+ ${Object.entries(E).map(([k,x])=>`${k}: ${x}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${M==null?void 0:M.quality}
34
- [selected track] ${C==null?void 0:C.quality}
35
- `});const se=C&&d&&d.history[C.id]&&oe()-d.history[C.id]<=s.trackCooldown&&(!d.last||C.id!==d.last.id);if(C!=null&&C.id&&d&&!se&&d.recordSelection(C),se&&(d!=null&&d.last)){const B=d.last;return d==null||d.recordSwitch(B),l({message:`
36
- [last selected] ${B==null?void 0:B.quality}
37
- `}),B}return d==null||d.recordSwitch(C),C};var Je=i=>new URL(i).hostname,H;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(H||(H={}));const cn=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Mt=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!cn(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return cn(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function Ee(){return oe()}function xo(i){return Ee()-i}function hn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function fp(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Zi(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,c,l,h=!1,f="arraybuffer",v=7e3,m=2e3,g=()=>{if(u)return;P(c);const M=xo(c);let C;if(M<m){C=m-M,setTimeout(g,C);return}m*=2,m>v&&(m=v),n&&n.abort(),n=new r,q()};const S=M=>(a=M,Z),E=M=>(l=M,Z),A=()=>(f="json",Z),w=()=>{if(!u){if(--d>=0){g(),s&&s();return}u=!0,l&&l(),t&&t()}},k=M=>(h=M,Z),q=()=>{c=Ee(),n=new r,n.open("get",i);let M=0,C,se=0;const B=()=>(P(c),Math.max(c,Math.max(C||0,se||0)));if(a&&n.addEventListener("progress",x=>{const X=Ee();a.updateChunk&&x.loaded>M&&(a.updateChunk(B(),x.loaded-M),M=x.loaded,C=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&a){const X=n.response.byteLength-M;X&&a.updateChunk&&a.updateChunk(B(),X)}n.responseType==="json"&&!Object.values(n.response).length?w():(l&&l(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){const x=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=Ee(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),Z},Z={withBitrateReporting:S,withParallel:k,withJSONResponse:A,withRetryCount:M=>(d=M,Z),withRetryInterval:(M,C)=>(L(M)&&(m=M),L(C)&&(v=C),Z),withTimeout:M=>(o=M,Z),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return Z}const pp=100,mp=2e3,vp=500;let gp=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,s){return{start:e,end:t,bytes:s}}_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-vp;if(t-e>mp){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>pp&&(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 Sp{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=Ee(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Ee()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Ee()}_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=Ee();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ui=1e4,ir=3,bp=6e4,yp=10,Tp=1,Ep=500;class $p{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 gp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=hn(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||L(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{fp(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Sp(ir,Ui,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,c=!1;const l=()=>{const w=a&&(!c||c===this.rep);return w||t("Not running!"),w},h=(w,k,q)=>{u&&u.abort(),u=Zi(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withTimeout(Ui).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ir).withFinally(()=>{u=null}).send()},f=(w,k,q)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),k,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=w=>{const k=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${k}=>${w}`),s.playbackRate=w)},m=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const q=Ee()-1e4;let j=0;for(let G=0;G<this.bufferStates.length;G++){const J=this.bufferStates[G];w=Math.min(w,J.buf),J.ts<q&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${w} drop=${j} jitter=${this.sourceJitter}`);let K=w-Tp;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?v(1.15):K>1?v(1.1):K>.3?v(1.05):v(1)}},S=w=>{let k;const q=()=>k&&k.start?k.start.length:0,j=x=>k.start[x]/1e3,K=x=>k.dur[x]/1e3,G=x=>k.fragIndex+x,J=(x,X)=>({chunkIdx:G(x),startTS:j(x),dur:K(x),discontinuity:X}),Z=()=>{let x=0;if(k&&k.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,de=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=X;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=k.dur.length-1;for(;ve>=0&&(fe-=k.dur[ve],!(fe<=0));--ve);x=Math.min(ve,k.dur.length-1-de),x=Math.max(x,0)}return J(x,!0)},M=x=>{const X=q();if(!(X<=0)){if(L(x)){for(let de=0;de<X;de++)if(j(de)>x)return J(de)}return Z()}},C=x=>{const X=q(),de=x?x.chunkIdx+1:0,fe=de-k.fragIndex;if(!(X<=0)){if(!x||fe<0||fe-X>yp)return t(`Resync: offset=${fe} bChunks=${X} chunk=`+JSON.stringify(x)),Z();if(!(fe>=X))return J(de-k.fragIndex,!1)}},se=(x,X,de)=>{d&&d.abort(),d=Zi(this.urlResolver.resolve(x,!0,this.lowLatency),X,de,()=>this._retryCallback()).withTimeout(Ui).withRetryCount(ir).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,X)=>{se(w,de=>{if(!l())return;k=de;const fe=!!k.lowLatency;fe!==this.lowLatency&&m(fe);let ve=0;for(let Ge=0;Ge<k.dur.length;++Ge)ve+=k.dur[Ge];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,x(M(X))},()=>this._handleNetworkError())},nextChunk:C}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{const{videoElement:k,logger:q}=this.params;let j=S(e.jidxUrl),K,G,J,Z,M=0,C,se,B;const x=()=>{C&&(clearTimeout(C),C=void 0);const z=Math.max(Ep,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+z,Ae=Ee(),ke=Math.min(1e4,be-Ae);M=Ae;const Nt=()=>{d||l()&&j.seek(()=>{l()&&(M=Ee(),X(),x())})};ke>0?C=window.setTimeout(()=>{this.paused?x():Nt()},ke):Nt()},X=()=>{let z;for(;z=j.nextChunk(Z);)Z=z,oi(z);const be=j.nextChunk(J);if(be){if(J&&be.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?x():(E(),this._initPlayerWith(e));return}Ge(be)}else x()},de=(z,be)=>{if(!l()||!this.sourceBuffer)return;let Ae,ke,Nt;const di=Xe=>{window.setTimeout(()=>{l()&&de(z,be)},Xe)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),di(100);else{const Xe=Ee(),De=k.currentTime;!this.paused&&k.buffered.length>1&&se===De&&Xe-B>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),se!==De&&(se=De,B=Xe);const Ft=this._getBufferSizeSec();if(Ft>30)q(`Buffered ${Ft} seconds; delaying appendBuffer`),di(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:Xe,buf:Ft}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(li){if(li.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),Nt=this.sourceBuffer.buffered.length,Nt!==0&&(Ae=this.sourceBuffer.buffered.start(0),ke=De,ke-Ae>4&&this.sourceBuffer.remove(Ae,ke-3)),di(1e3);else throw li}}},fe=()=>{G&&K&&(q([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(J)]),de(G,function(){G=null,X()}))},ve=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Ge=z=>{l()&&f(ve(z),(be,Ae)=>{if(l()){if(Ae/=1e3,G=be,J=z,n=z.startTS,Ae){const ke=Math.min(10,z.dur/Ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}fe()}},()=>this._handleNetworkError())},oi=z=>{l()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(z),!1)))},Bt=z=>{l()&&(e.cachedHeader=z,de(z,()=>{K=!0,fe()}))};a=!0,j.seek(z=>{if(l()){if(M=Ee(),!z){x();return}Z=z,!Q(w)||z.startTS>w?Ge(z):(J=z,X())}},w),e.cachedHeader?Bt(e.cachedHeader):h(e.headerUrl,Bt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),L(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return L(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=l=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(f=this._getBufferSizeSec(),v=l/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(h,f)=>{const v=Ee();if(this.chunkRateEstimator.addInterval(h,v,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:g}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&xo(n)<3e4)return;s(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{const f=a.updateChunk(l,h);return f&&d(),f},notifySwitch:l=>{const h=Ee();l<o&&(n=h),o=l}}}_fetchManifest(e,t,s){this.manifestRequest=Zi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Ui).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;Mt(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(H.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({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))},bp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class _o{constructor(){this.onDroopedVideoFramesLimit$=new R,this.subscription=new ie,this.playing=!1,this.tracks=[],this.forceChecker$=new R,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Pt(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&Zt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}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(I(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=pi(this.droppedFramesChecker.checkTime).pipe(ce(()=>this.playing),ce(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Ke(this.droppedFramesChecker.checkTime)),s=N(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>zi(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}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 _r=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},ni=(i,e)=>new Br(t=>{if(!window.IntersectionObserver)return;const s={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||_r()))},{...s,...e});r.observe(i);const a=I(document,"visibilitychange").pipe($(n=>!document.hidden||_r())).subscribe(n=>t.next(n));return()=>{r.unobserve(i),a.unsubscribe}}),Ap=[H.PAUSED,H.PLAYING,H.READY],wp=[H.PAUSED,H.PLAYING,H.READY];class kp{constructor(e){this.subscription=new ie,this.videoState=new ue(H.STOPPED),this.representations$=new y([]),this.textTracksManager=new mt,this.droppedFramesManager=new _o,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Zr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,c=[];for(const l of d){const h=(a=l.name)!==null&&a!==void 0?a:l.index.toString(10),f=(n=Ss(l.name))!==null&&n!==void 0?n:kt(l.video),v=l.bitrate/1e3,m={...l.video};if(!f)continue;const g={id:h,quality:f,bitrate:v,size:m};c.push({track:g,representation:l})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:l})=>l)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,c=(u=this.representations$.getValue().find(({representation:l})=>l===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),L(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:d,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(wp.includes(r)&&(d||c)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===Y.Requested&&Ap.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Ve(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(n===p.PAUSED)this.videoState.setState(H.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const l=o==null?void 0:o.from;l&&l===p.READY&&this.dash.catchUp(),this.dash.play()}return;case H.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(n===p.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 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(Ve(this.params.source.url,l))}return;default:return U(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.WTF,message:"DashLiveProvider internal logic error",thrown:r})};N(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Rt(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(Je(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 s=Ot(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe($(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===H.READY&&this.videoState.setState(H.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ie({zeroTime:this.zeroTime$.pipe(ce(L)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ai(this.video,this.params.desiredState.isLooped,t)).add(Ct(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ai(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ni(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&vd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case H.MANIFEST_READY:case H.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return U(r.to)}},t)).add(N(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Oe(["init"])).pipe(Ke(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),It(this.video)}createLiveDashPlayer(){const e=new $p({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!d&&L(u)?u:bs(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),l=c==null?void 0:c.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(h||l!==f)&&this.setVideoTrack(c),v&&this.setAutoQuality(d),h||v||l!==f){const m=(n=o.find(({track:g})=>g.id===l))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e.id}`),this.dash.switchByName(s.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(),s=this.videoState.getState(),r=t===p.PAUSED&&s===H.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ve(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var je;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(je||(je={}));var ns;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ns||(ns={}));var Ce;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ce||(Ce={}));var F;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(F||(F={}));var ti;(function(i){i.MP4="mp4",i.WEBM="webm"})(ti||(ti={}));var os;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(os||(os={}));var ne;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ne||(ne={}));var mi=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};class fn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Ro extends fn{constructor(){super(),this.listeners||fn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),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 Io=class{constructor(){Object.defineProperty(this,"signal",{value:new Ro,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Io.prototype[Symbol.toStringTag]="AbortController",Ro.prototype[Symbol.toStringTag]="AbortSignal");function Co(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 Pp(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Co({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,c){let l;c&&c.signal&&(l=c.signal,delete c.signal);const h=new t(d,c);return l&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const c=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(c){let l;try{l=new DOMException("Aborted","AbortError")}catch(f){l=new Error("Aborted"),l.name="AbortError"}if(c.aborted)return Promise.reject(l);const h=new Promise((f,v)=>{c.addEventListener("abort",()=>v(l),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const ys=Co({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Oo=ys?Pp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bi=ys?Oo.fetch:window.fetch;ys?Oo.Request:window.Request;const ei=ys?Io:window.AbortController;var Rr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Lp=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Dp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",pn=Dp?Lp:window.requestIdleCallback;var sr,rr;const xp=16;let Mo=!1;try{Mo=Mr().browser===Nn.Safari&&parseInt((rr=(sr=navigator.userAgent.match(/Version\/(\d+)/))===null||sr===void 0?void 0:sr[1])!==null&&rr!==void 0?rr:"",10)<=xp}catch(i){console.error(i)}class _p{constructor(e){this.bufferFull$=new R,this.error$=new R,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:_.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Mo&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:_.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:U(t)}}}var mn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Le{get id(){return this.type}get size(){return this.size32}constructor(e,t){this.cursor=0,this.source=e,this.boxParser=t,this.children=[];const s=this.readUint32();this.type=this.readString(4),this.size32=s<=e.buffer.byteLength-e.byteOffset?s:NaN;const r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Bo extends Le{}class Rp extends Le{}class Ip extends Le{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let s=this.size-this.cursor;for(;s;){const r=this.readString(4);this.compatibleBrands.push(r),s-=4}}}class Cp extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Op extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Mp extends Le{constructor(e,t){super(e,t),this.data=this.content}}class lt extends Le{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class No extends lt{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 s=0;s<this.referenceCount;s++){let r=this.readUint32();const a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const u=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Bp extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Np extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var wt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(wt||(wt={}));class Fp extends lt{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=wt.MONOSCOPIC;break;case 1:this.stereoMode=wt.TOP_BOTTOM;break;case 2:this.stereoMode=wt.LEFT_RIGHT;break;case 3:this.stereoMode=wt.STEREO_CUSTOM;break;case 4:this.stereoMode=wt.RIGHT_LEFT;break}this.cursor+=1}}class Vp extends lt{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Up extends lt{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Hp extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Gp extends lt{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 Yp extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class qp extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class jp extends lt{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class Wp extends Le{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class zp extends lt{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 Qp extends lt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Kp extends lt{constructor(e,t){super(e,t),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let s=0;s<this.sampleCount;s++)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 ae;(function(i){i.FtypBox="ftyp",i.MoovBox="moov",i.MoofBox="moof",i.MdatBox="mdat",i.SidxBox="sidx",i.TrakBox="trak",i.MdiaBox="mdia",i.MfhdBox="mfhd",i.TkhdBox="tkhd",i.TrafBox="traf",i.TfhdBox="tfhd",i.TfdtBox="tfdt",i.TrunBox="trun",i.MinfBox="minf",i.Sv3dBox="sv3d",i.St3dBox="st3d",i.PrhdBox="prhd",i.ProjBox="proj",i.EquiBox="equi",i.UuidBox="uuid",i.UnknownBox="unknown"})(ae||(ae={}));const Jp={[ae.FtypBox]:Ip,[ae.MoovBox]:Cp,[ae.MoofBox]:Op,[ae.MdatBox]:Mp,[ae.SidxBox]:No,[ae.TrakBox]:Bp,[ae.MdiaBox]:Hp,[ae.MfhdBox]:jp,[ae.TkhdBox]:Gp,[ae.TrafBox]:Wp,[ae.TfhdBox]:zp,[ae.TfdtBox]:Qp,[ae.TrunBox]:Kp,[ae.MinfBox]:Yp,[ae.Sv3dBox]:Np,[ae.St3dBox]:Fp,[ae.PrhdBox]:Vp,[ae.ProjBox]:qp,[ae.EquiBox]:Up,[ae.UuidBox]:Rp,[ae.UnknownBox]:Bo};class Lt{constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;)try{const a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+s));if(!n.size)break;t.push(n),s+=n.size}catch(r){break}return t}createBox(e,t){const s=Jp[e];return s?new s(t,new Lt):new Bo(t,new Lt)}}class ta{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var s,r,a;(s=(r=this.index)[a=t.type])!==null&&s!==void 0||(r[a]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const Xp=new TextDecoder("ascii"),Zp=i=>Xp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",em=i=>{const e=new No(i,new Lt);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:F.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},tm=(i,e)=>{const s=new Lt().parse(i),r=new ta(s),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;const o=a[0],u=n[n.length-1],d=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,d,l)},im=(i,e)=>{const s=new Lt().parse(i),a=new ta(s).findAll("traf"),n=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun");let d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,h)=>l+h,0):d=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},sm=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new Lt().parse(i),r=new ta(s);if(r.find("sv3d")){e.is3dVideo=!0;const n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},rm={validateData:Zp,parseInit:sm,getIndexRange:()=>{},parseSegments:em,parseFeedableSegmentChunk:tm,getSegmentEndTime:im};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var D;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(D||(D={}));const vn={[T.EBML]:{type:D.Master},[T.EBMLVersion]:{type:D.UnsignedInteger},[T.EBMLReadVersion]:{type:D.UnsignedInteger},[T.EBMLMaxIDLength]:{type:D.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[T.DocType]:{type:D.String},[T.DocTypeVersion]:{type:D.UnsignedInteger},[T.DocTypeReadVersion]:{type:D.UnsignedInteger},[T.Void]:{type:D.Binary},[T.Segment]:{type:D.Master},[T.SeekHead]:{type:D.Master},[T.Seek]:{type:D.Master},[T.SeekID]:{type:D.Binary},[T.SeekPosition]:{type:D.UnsignedInteger},[T.Info]:{type:D.Master},[T.TimestampScale]:{type:D.UnsignedInteger},[T.Duration]:{type:D.Float},[T.Tracks]:{type:D.Master},[T.TrackEntry]:{type:D.Master},[T.Video]:{type:D.Master},[T.Projection]:{type:D.Master},[T.ProjectionType]:{type:D.UnsignedInteger},[T.ProjectionPrivate]:{type:D.Master},[T.Chapters]:{type:D.Master},[T.Cluster]:{type:D.Master},[T.Timestamp]:{type:D.UnsignedInteger},[T.SilentTracks]:{type:D.Master},[T.SilentTrackNumber]:{type:D.UnsignedInteger},[T.Position]:{type:D.UnsignedInteger},[T.PrevSize]:{type:D.UnsignedInteger},[T.SimpleBlock]:{type:D.Binary},[T.BlockGroup]:{type:D.Master},[T.EncryptedBlock]:{type:D.Binary},[T.Attachments]:{type:D.Master},[T.Tags]:{type:D.Master},[T.Cues]:{type:D.Master},[T.CuePoint]:{type:D.Master},[T.CueTime]:{type:D.UnsignedInteger},[T.CueTrackPositions]:{type:D.Master},[T.CueTrack]:{type:D.UnsignedInteger},[T.CueClusterPosition]:{type:D.UnsignedInteger},[T.CueRelativePosition]:{type:D.UnsignedInteger},[T.CueDuration]:{type:D.UnsignedInteger},[T.CueBlockNumber]:{type:D.UnsignedInteger},[T.CueCodecState]:{type:D.UnsignedInteger},[T.CueReference]:{type:D.Master},[T.CueRefTime]:{type:D.UnsignedInteger}},Fo=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=ds(i,t),r=s in vn,a=r?vn[s].type:D.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,c=ds(u),l=d*2**((o-1)*8)+c,h=t+o;let f;return h+l>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,l),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+l,value:f,valueSize:l}},ds=(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:{const t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(i,e)=>{switch(e){case D.SignedInteger:return i.getInt8(0);case D.UnsignedInteger:return ds(i);case D.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(i);case D.UTF8:return new TextDecoder("utf-8").decode(i);case D.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case D.Master:return i;case D.Binary:return i;default:U(e)}},ii=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Fo(s);if(!e(r))return;r.type===D.Master&&ii(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},am=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Fo(i);return ii(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=ze(o,n):a===T.DocType?t=ze(o,n):a===T.DocTypeReadVersion&&(s=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Vo=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],nm=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],om=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d,c=!1;const l=0;return ii(i,({tag:h,type:f,value:v,valueSize:m})=>{if(h===T.SeekID){const g=ze(v,f);d=ds(g)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=v.byteOffset,t=v.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=ze(v,f):h===T.Duration?r=ze(v,f):h===T.SeekPosition&&d===T.Cues?u=ze(v,f):h===T.Tracks?ii(v,({tag:g,type:S,value:E})=>g===T.ProjectionType?(c=ze(E,S)===1,!1):!0):a&&n&&Vo.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:l,projectionType:os.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dm=i=>{if(Q(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lm=(i,e)=>{let t=!1,s=!1;const r=o=>L(o.time)&&L(o.position),a=[];let n;return ii(i,({tag:o,type:u,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=ze(d,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=ze(d,u));break;default:t&&Vo.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:c}=o,l=a[u+1];return{status:F.NONE,time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},um=i=>{let e=0,t=!1;try{ii(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):nm.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},cm={validateData:am,parseInit:om,getIndexRange:dm,parseSegments:lm,parseFeedableSegmentChunk:um};var hm=Dt,fm=cs,pm=He,mm=pm("match"),vm=function(i){var e;return hm(i)&&((e=i[mm])!==void 0?!!e:fm(i)=="RegExp")},gm=gs,Sm=String,bm=function(i){if(gm(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Sm(i)},ym=_t,Tm=function(){var i=ym(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},Em=ot,$m=dt,Am=Hr,wm=Tm,gn=RegExp.prototype,km=function(i){var e=i.flags;return e===void 0&&!("flags"in gn)&&!$m(i,"flags")&&Am(gn,i)?Em(wm,i):e},ia=nt,Pm=ps,Lm=Math.floor,ar=ia("".charAt),Dm=ia("".replace),nr=ia("".slice),xm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,_m=/\$([$&'`]|\d{1,2})/g,Rm=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=_m;return r!==void 0&&(r=Pm(r),u=xm),Dm(a,u,function(d,c){var l;switch(ar(c,0)){case"$":return"$";case"&":return i;case"`":return nr(e,0,t);case"'":return nr(e,n);case"<":l=r[nr(c,1,-1)];break;default:var h=+c;if(h===0)return d;if(h>o){var f=Lm(h/10);return f===0?d:f<=o?s[f-1]===void 0?ar(c,1):s[f-1]+ar(c,1):d}l=s[h-1]}return l===void 0?"":l})},Im=vs,Cm=ot,sa=nt,Sn=Fr,Om=Me,Mm=hs,Bm=vm,jt=bm,Nm=fs,Fm=km,Vm=Rm,Um=He,Hm=Um("replace"),Gm=TypeError,Uo=sa("".indexOf),Ym=sa("".replace),bn=sa("".slice),qm=Math.max,yn=function(i,e,t){return t>i.length?-1:e===""?t:Uo(i,e,t)};Im({target:"String",proto:!0},{replaceAll:function(e,t){var s=Sn(this),r,a,n,o,u,d,c,l,h,f=0,v=0,m="";if(!Mm(e)){if(r=Bm(e),r&&(a=jt(Sn(Fm(e))),!~Uo(a,"g")))throw Gm("`.replaceAll` does not allow non-global regexes");if(n=Nm(e,Hm),n)return Cm(n,e,s,t);if(r)return Ym(jt(s),e,t)}for(o=jt(s),u=jt(e),d=Om(t),d||(t=jt(t)),c=u.length,l=qm(1,c),f=yn(o,u,0);f!==-1;)h=d?jt(t(u,f,o)):Vm(u,o,f,[],void 0,t),m+=bn(o,v,f)+h,v=f+c,f=yn(o,u,f+l);return v<o.length&&(m+=bn(o,v)),m}});var jm=Do,Wm=jm("String","replaceAll"),zm=Wm,Qm=zm,Km=Qm,Jm=Km,Tn=Nr(Jm);const Xm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},En=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?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),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Qt=(i,e)=>{let t=i;t=Tn(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Tn(t,n,(o,u)=>Q(a)?o:Q(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Zm=(i,e)=>{var t,s,r,a,n,o,u,d,c,l,h,f,v,m,g,S,E,A,w,k,q,j,K,G,J,Z,M,C,se,B,x,X,de,fe,ve,Ge,oi,Bt,z,be,Ae,ke;const di=new DOMParser().parseFromString(i,"application/xml"),Xe={video:[],audio:[],text:[]},De=di.children[0],Ft=De.getElementsByTagName("Period")[0],li=(r=(s=(t=De.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",zo=Ft.children,Qo=De.getAttribute("type")==="dynamic",na=De.getAttribute("availabilityStartTime"),Ko=na?new Date(na).getTime():void 0;let vt;const oa=De.getAttribute("mediaPresentationDuration"),da=Ft.getAttribute("duration"),Ts=De.getElementsByTagName("vk:Attrs")[0],la=Ts==null?void 0:Ts.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(oa)vt=En(oa);else if(da){const xe=En(da);L(xe)&&(vt=xe)}else la&&(vt=parseInt(la,10));let Jo=0;const Es=(n=(a=De.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Xo=Es.includes(ns.WEBM_AS_IN_FFMPEG)||Es.includes(ns.WEBM_AS_IN_SPEC)?ti.WEBM:ti.MP4;for(const xe of zo){const wi=xe.getAttribute("mimeType"),Zo=xe.getAttribute("codecs"),ua=(o=xe.getAttribute("contentType"))!==null&&o!==void 0?o:wi==null?void 0:wi.split("/")[0],ed=(d=(u=xe.getAttribute("profiles"))===null||u===void 0?void 0:u.split(","))!==null&&d!==void 0?d:[],ca=xe.querySelectorAll("Representation"),td=xe.querySelector("SegmentTemplate");if(ua===Se.TEXT){for(const pe of ca){const ut=pe.getAttribute("id")||"",ki=xe.getAttribute("lang"),Vt=xe.getAttribute("label"),$s=(h=(l=(c=pe.querySelector("BaseURL"))===null||c===void 0?void 0:c.textContent)===null||l===void 0?void 0:l.trim())!==null&&h!==void 0?h:"",As=new URL($s||li,e).toString(),Pi=ut.includes("_auto");Xe[Se.TEXT].push({id:ut,lang:ki,label:Vt,isAuto:Pi,kind:Se.TEXT,url:As})}continue}for(const pe of ca){const ut=(f=pe.getAttribute("mimeType"))!==null&&f!==void 0?f:wi,ki=(m=(v=pe.getAttribute("codecs"))!==null&&v!==void 0?v:Zo)!==null&&m!==void 0?m:"",Vt=(S=(g=pe.getAttribute("contentType"))!==null&&g!==void 0?g:ut==null?void 0:ut.split("/")[0])!==null&&S!==void 0?S:ua,$s=(A=(E=xe.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&A!==void 0?A:[],As=parseInt((w=pe.getAttribute("width"))!==null&&w!==void 0?w:"",10),Pi=parseInt((k=pe.getAttribute("height"))!==null&&k!==void 0?k:"",10),ha=parseInt((q=pe.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,fa=(j=pe.getAttribute("frameRate"))!==null&&j!==void 0?j:"",id=(K=pe.getAttribute("quality"))!==null&&K!==void 0?K:void 0,sd=fa?Xm(fa):void 0,rd=(G=pe.getAttribute("id"))!==null&&G!==void 0?G:(Jo++).toString(10),ad=Vt==="video"?`${Pi}p`:Vt==="audio"?`${ha}Kbps`:ki,nd=`${rd}@${ad}`,od=(M=(Z=(J=pe.querySelector("BaseURL"))===null||J===void 0?void 0:J.textContent)===null||Z===void 0?void 0:Z.trim())!==null&&M!==void 0?M:"",pa=new URL(od||li,e).toString(),dd=[...Es,...ed,...$s];let ws;const ld=pe.querySelector("SegmentBase"),gt=(C=pe.querySelector("SegmentTemplate"))!==null&&C!==void 0?C:td;if(ld){const St=(B=(se=pe.querySelector("SegmentBase Initialization"))===null||se===void 0?void 0:se.getAttribute("range"))!==null&&B!==void 0?B:"",[bt,Ps]=St.split("-").map(Ut=>parseInt(Ut,10)),ct={from:bt,to:Ps},ui=(x=pe.querySelector("SegmentBase"))===null||x===void 0?void 0:x.getAttribute("indexRange"),[Ls,Li]=ui?ui.split("-").map(Ut=>parseInt(Ut,10)):[],ci=ui?{from:Ls,to:Li}:void 0;ws={type:Ce.BYTE_RANGE,url:pa,initRange:ct,indexRange:ci}}else if(gt){const St={representationId:(X=pe.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(de=pe.getAttribute("bandwidth"))!==null&&de!==void 0?de:void 0},bt=parseInt((fe=gt.getAttribute("timescale"))!==null&&fe!==void 0?fe:"",10),Ps=(ve=gt.getAttribute("initialization"))!==null&&ve!==void 0?ve:"",ct=gt.getAttribute("media"),ui=(oi=parseInt((Ge=gt.getAttribute("startNumber"))!==null&&Ge!==void 0?Ge:"",10))!==null&&oi!==void 0?oi:1,Ls=Qt(Ps,St);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");const Li=(Bt=gt.querySelectorAll("SegmentTimeline S"))!==null&&Bt!==void 0?Bt:[],ci=[];let Ut=0,Ds="",xs=0;if(Li.length){let Di=ui,Be=0;for(const Ht of Li){const Ye=parseInt((z=Ht.getAttribute("d"))!==null&&z!==void 0?z:"",10),yt=parseInt((be=Ht.getAttribute("r"))!==null&&be!==void 0?be:"",10)||0,xi=parseInt((Ae=Ht.getAttribute("t"))!==null&&Ae!==void 0?Ae:"",10);Be=Number.isFinite(xi)?xi:Be;const _s=Ye/bt*1e3,Rs=Be/bt*1e3;for(let _i=0;_i<yt+1;_i++){const cd=Qt(ct,{...St,segmentNumber:Di.toString(10),segmentTime:(Be+_i*Ye).toString(10)}),ma=(Rs!=null?Rs:0)+_i*_s,hd=ma+_s;Di++,ci.push({time:{from:ma,to:hd},url:cd})}Be+=(yt+1)*Ye,Ut+=(yt+1)*_s}xs=Be/bt*1e3,Ds=Qt(ct,{...St,segmentNumber:Di.toString(10),segmentTime:Be.toString(10)})}else if(L(vt)){const Be=parseInt((ke=gt.getAttribute("duration"))!==null&&ke!==void 0?ke:"",10)/bt*1e3,Ht=Math.ceil(vt/Be);let Ye=0;for(let yt=1;yt<Ht;yt++){const xi=Qt(ct,{...St,segmentNumber:yt.toString(10),segmentTime:Ye.toString(10)});ci.push({time:{from:Ye,to:Ye+Be},url:xi}),Ye+=Be}xs=Ye,Ds=Qt(ct,{...St,segmentNumber:Ht.toString(10),segmentTime:Ye.toString(10)})}const ud={time:{from:xs,to:1/0},url:Ds};ws={type:Ce.TEMPLATE,baseUrl:pa,segmentTemplateUrl:ct,initUrl:Ls,totalSegmentsDurationMs:Ut,segments:ci,nextSegmentBeyondManifest:ud,timescale:bt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Vt||!ut)continue;const ks={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[Vt];ks&&Xe[ks].push({id:nd,kind:ks,segmentReference:ws,profiles:dd,duration:vt,bitrate:ha,mime:ut,codecs:ki,width:As,height:Pi,fps:sd,quality:id})}}return{dynamic:Qo,liveAvailabilityStartTime:Ko,duration:vt,container:Xo,representations:Xe}},ev=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Ss(a):void 0)!==null&&n!==void 0?n:kt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},tv=({id:i,bitrate:e})=>({id:i,bitrate:e}),iv=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=et(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:et(i,-1)},sv=({id:i,lang:e,label:t,url:s,isAuto:r})=>({id:i,url:s,isAuto:r,type:"internal",language:e,label:t}),$n=i=>"url"in i,Wt=i=>i.type===Ce.TEMPLATE,Ir=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class An{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:c}){switch(this.currentSegmentLength$=new y(0),this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.playingRepresentationInit$=new y(void 0),this.error$=new R,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ei,this.destroyAbortController=new ei,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=we(this.destroyAbortController.signal,async function*(l){const h=this.representations.get(l);P(h,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new _p(this.sourceBuffer),this.subscription.add(I(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(I(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,mn(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),v=this.segments.get(h.id),m=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(v,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(v,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=we(this.destroyAbortController.signal,async function*(l){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return;this.switchingToRepresentationId=l;const h=this.representations.get(l);P(h,`No such representation ${l}`);let f=this.segments.get(l),v=this.initData.get(l);if(Q(v)||Q(f)?yield this.loadInit(h,"high",!1):v instanceof Promise&&(yield v),f=this.segments.get(l),P(f,"No segments for starting representation"),v=this.initData.get(l),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal);const m=this.getCurrentPosition();L(m)&&(this.isLive||(f.forEach(g=>g.status=F.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=we(this.destroyAbortController.signal,async function*(l){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return;for(const E of this.representations.keys()){const A=l.find(q=>q.id===E);A&&this.representations.set(E,A);const w=this.representations.get(E);if(!w||!Wt(w.segmentReference))return;const k=this.getActualLiveStartingSegments(w.segmentReference);this.segments.set(w.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,v=this.representations.get(f);P(v);const m=this.segments.get(f);P(m,"No segments for starting representation");const g=this.initData.get(f);if(P(g,"No init buffer for starting representation"),!(g instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(m,v),yield this.sourceBufferTaskQueue.append(g,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=s,s){case ti.MP4:this.containerParser=rm;break;case ti.WEBM:this.containerParser=cm;break;default:U(s)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ei,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var t,s;if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const r=this.representations.get(this.downloadingRepresentationId),a=this.segments.get(this.downloadingRepresentationId);if(P(r,`No such representation ${this.downloadingRepresentationId}`),!a)return;const n=a.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next(((t=n==null?void 0:n.time.to)!==null&&t!==void 0?t:0)-((s=n==null?void 0:n.time.from)!==null&&s!==void 0?s:0));let o=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=mi(this.sourceBuffer.buffered,e),f=n?n.time.to+100:-1/0;n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+100&&(o=f)}if(isFinite(this.bufferLimit)&&mn(this.sourceBuffer.buffered)>=this.bufferLimit){const l=mi(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<h);return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(a,r.segmentReference.type,o),d.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if(d.includes(n))l="high";else{const h=et(d,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(d,r,l)}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status===F.FED&&!d.length&&mi(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=et(a,-1);c&&c.status===F.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(n===c))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;L(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Wt(n.segmentReference))return;const o=n.segmentReference.segments.map(l=>({...l,status:F.NONE,size:void 0})),u=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=et(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,c=o==null?void 0:o.findIndex(l=>Math.floor(d)>=Math.floor(l.time.from)&&Math.floor(d)<=Math.floor(l.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const l=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,l)}else{const l=o.slice(c+1);this.segments.set(n.id,[...u,...l])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!Wt(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Qt(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:F.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:l,time:{from:h,to:f}},v)=>{const m=h<=s&&f>=s,g=h>s||m||v===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(l===F.NONE||l===F.PARTIALLY_EJECTED&&g&&E&&this.sourceBuffer&&!Rr(this.sourceBuffer.buffered,s))&&g&&E});if(r===-1)return[];if(t!==Ce.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(n<=d||o<=c);l++){const h=a[l];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===F.NONE||h.status===F.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,s="auto"){t.segmentReference.type===Ce.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=F.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await we(o,async function*(){const c=Qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const c=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:s,isLowLatency:this.isActiveLowLatency()});if(!c)return;const l=new DataView(c);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(l,h)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(l,o),r.segment.status=F.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ir(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const u of e)u.status=F.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await we(n,async function*(){const u=Qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),I(window,"online").pipe(Te()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ir(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:et(e,0).byte.from,to:et(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:s,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{const l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,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:s,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(u.status=F.PARTIALLY_FED,o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const c of this.activeSegments){const{segment:l}=c,h=u===Ce.BYTE_RANGE,f=h?l.byte.to-l.byte.from+1:d;if(c.representationId!==t||!(!h||l.byte.from>=s&&l.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?l.byte.from-s:0,g=h?l.byte.to-s:e.byteLength,S=m<r,E=g<=r;if(l.status===F.DOWNLOADING&&S&&E){l.status=F.DOWNLOADED;const A=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append(A,a).then(w=>w&&!a.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(f,r-m),c.loadedBytes>c.feedingBytes)){const A=new DataView(e.buffer,e.byteOffset+m+c.feedingBytes,c.loadedBytes-c.feedingBytes),w=c.loadedBytes===f?A:this.containerParser.parseFeedableSegmentChunk(A);w!=null&&w.byteLength&&(l.status=F.PARTIALLY_FED,c.feedingBytes+=w.byteLength,this.sourceBufferTaskQueue.append(w,a).then(k=>{if(a.aborted)n();else if(k)c.fedBytes+=w.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=F.FED,$n(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===F.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=F.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===F.PARTIALLY_FED||e.status===F.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=F.NONE),e.status=F.PARTIALLY_EJECTED):e.status=F.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=pn(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?we(this.destroyAbortController.signal,async function*(){const o=Qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:u,dataView:d,segments:c}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let h=c;this.isLive&&Wt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var c;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const l=$n(d)?(c=d.size)!==null&&c!==void 0?c:0:d.byte.to-d.byte.from;r+=l};for(const d of this.segments.values())for(const c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===F.FED&&u(c)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===F.FED&&u(c)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const c=this.sourceBuffer.buffered.start(d)*1e3,l=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===F.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(l)){a=c,n=l;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const l of c)l.time.from>e+d&&l.status===F.FED&&u(l)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=pn(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==F.FED&&a!==F.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),d=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1||this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status=F.PARTIALLY_EJECTED:r.status=F.NONE)}}}var Cr=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},rv=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?yr.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Xt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Xt||(Xt={}));class av{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new ei,this.subscription=new ie,this.fetchManifest=we(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Cr(a));const n=yield bi(a,{signal:this.abortAllController.signal}).catch(hi);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=we(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Xt.HEADER:Xt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:c=!0,isLowLatency:l=!1}={}){var h,f;let v=r;const m=new Headers;if(n)switch(a){case Xt.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case Xt.PARAM:{const C=new URL(v,location.href);C.searchParams.append("bytes",`${n.from}-${n.to}`),v=C.toString();break}default:U(a)}this.requestQuic&&(v=Cr(v));let g=this.abortAllController.signal,S;if(d){const C=new ei;if(S=N(I(this.abortAllController.signal,"abort"),I(d,"abort")).subscribe(()=>{try{C.abort()}catch(se){hi(se)}}),this.abortAllController.signal.aborted||d.aborted)try{C.abort()}catch(se){hi(se)}g=C.signal}const E=oe(),A=yield bi(v,{priority:u,headers:m,signal:g}).catch(hi),w=oe();if(!A)return S==null||S.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(w-E),!A.ok||!A.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));if(this.onHeadersReceived(A.headers),!o&&!c)return S==null||S.unsubscribe(),A.arrayBuffer();const[k,q]=A.body.tee(),j=k.getReader();c&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,l));let K=0,G=new Uint8Array(0),J=!1;const Z=C=>{S==null||S.unsubscribe(),J=!0,hi(C)},M=we(g,async function*({done:C,value:se}){if(K===0&&this.lastRequestFirstBytes$.next(oe()-E),g.aborted){S==null||S.unsubscribe();return}if(!C&&se){const B=new Uint8Array(G.length+se.length);B.set(G),B.set(se,G.length),G=B,K+=se.byteLength,o==null||o(new DataView(G.buffer),K),yield j==null?void 0:j.read().then(M,Z)}}.bind(this));return yield j==null?void 0:j.read().then(M,Z),S==null||S.unsubscribe(),J?null:G.buffer}.bind(this)),this.fetchByteRangeRepresentation=we(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Ce.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let c=u,l=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(c=Math.min(f,u),l=Math.max(v,d))),c=Math.min(c,0);const m=yield this.fetch(r.url,{range:{from:c,to:l},priority:n,measureThroughput:!1});if(!m)return null;const g=new DataView(m,u-c,d-c+1);if(!a.validateData(g))throw new Error("Invalid media file");const S=a.parseInit(g),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(m,E.from-c,E.to-E.from+1);else{const k=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!k)return null;A=new DataView(k)}const w=a.parseSegments(A,S,E);return{init:S,dataView:new DataView(m),segments:w}}.bind(this)),this.fetchTemplateRepresentation=we(this.abortAllController.signal,async function*(r,a){if(r.type!==Ce.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:F.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=rv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var r,a;const{type:n}=e;switch(n){case Ce.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ce.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:U(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const hi=i=>{if(!Ir(i))throw i},Kt=1e3,ls=(i,e,t)=>t*e+(1-t)*i,Ho=(i,e)=>i.reduce((t,s)=>t+s,0)/e,nv=(i,e,t,s)=>{let r=0,a=t;const n=Ho(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class ra{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new We(`raw_${s}`),this.smoothedSeries$=new We(`smoothed_${s}`),this.reportedSeries$=new We(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||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 ov extends ra{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ls(this.slow,e,this.params.emaAlphaSlow),this.fast=ls(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class dv extends ra{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Ho(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ls(this.emaSmoothed,e,this.params.emaAlpha);const s=nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class lv extends ra{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?ls(this.smoothed,e,this.params.emaAlpha):e}}class Or{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new ov({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new dv({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new lv({initial:e,label:"liveEdgeDelay",...t})}}const uv=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Tt=()=>window.ManagedMediaSource||window.MediaSource,Go=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cv=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},hv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,wn=["timeupdate","progress","play","seeked","stalled","waiting"];var Re;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Re||(Re={}));let fv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ie,this.representationSubscription=new ie,this.state$=new ue(Re.NONE),this.currentVideoRepresentation$=new y(void 0),this.currentVideoRepresentationInit$=new y(void 0),this.currentVideoSegmentLength$=new y(0),this.currentAudioSegmentLength$=new y(0),this.error$=new R,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.isLive$=new y(!1),this.liveDuration$=new y(0),this.liveAvailabilityStartTime$=new y(void 0),this.bufferLength$=new y(0),this.liveLoadBufferLength$=new y(0),this.livePositionFromPlayer$=new y(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new R,this.gapWatchdogStarted=!1,this.destroyController=new ei,this.initManifest=we(this.destroyController.signal,async function*(t,s,r){var a;this.element=t,this.manifestUrlString=Ve(s,r,me.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Re.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Re.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=we(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n})});if(!s)return null;let r;try{r=Zm(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:_.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,c,l,h;return!!(!((c=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||c===void 0)&&c.call(d,o)&&(!((h=(l=Tt())===null||l===void 0?void 0:l.isTypeSupported)===null||h===void 0)&&h.call(l,`${o}; codecs="${u}"`))||n===Se.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:as(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=we(this.destroyController.signal,async function*(t,s,r){var a;P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Re.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(I(m,"error").pipe(ce(g=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:_.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?hv():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Go())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const u={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 An(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,u),this.bufferManagers=[this.videoBufferManager],L(s)&&(this.audioBufferManager=new An(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,u),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(pi(Kt).subscribe(m=>{var g;if(!((g=this.element)===null||g===void 0)&&g.paused){const S=dn(this.manifestUrlString,me.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ve(this.manifestUrlString,S+Kt,me.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(N(...wn.filter(m=>m!=="waiting").map(m=>I(this.element,m))).pipe($(m=>this.element?mi(this.element.buffered,this.element.currentTime*1e3):0),he(),ce(m=>!!m),gi(m=>{var g;(g=this.stallWatchdogSubscription)===null||g===void 0||g.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ce(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=g-S;let k=1+Math.sign(w)*A;Math.abs(w)<E?k=1:Math.abs(w)>E*2&&(k=1+Math.sign(w)*A*2),uv(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var S,E;let A=0;if(g){const w=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;A=Math.min(...this.bufferManagers.map(q=>{var j,K;return(K=(j=q.getLiveSegmentsToLoadState(this.manifest))===null||j===void 0?void 0:j.to)!==null&&K!==void 0?K:w}))-w}this.liveLoadBufferLength$.getValue()!==A&&this.liveLoadBufferLength$.next(A)}));let m=0;this.representationSubscription.add(Ie({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gd(Kt)).subscribe(async({liveLoadBufferLength:g,bufferLength:S})=>{if(P(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,A=dn(this.manifestUrlString,me.DASH_CMAF_OFFSET_P),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,j=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,K=this.isActiveLowLatency?S:g;let G=je.None;if(this.isActiveLowLatency?G=je.ActiveLowLatency:K<k+j&&K>=k?G=je.LiveWithTargetOffset:A!==0&&K<k&&(G=je.LiveForwardBuffering),isFinite(g)&&(m=g>m?g:m),G===je.LiveForwardBuffering||G===je.LiveWithTargetOffset){const J=m-(k+q),Z=this.normolizeLiveOffset(Math.trunc(A+J/E)),M=Math.abs(Z-A);let C;!g||M<=this.tuning.dashCmafLive.offsetCalculationError?C=A:Z>0&&M>this.tuning.dashCmafLive.offsetCalculationError?C=Z:C=0,this.manifestUrlString=Ve(this.manifestUrlString,C,me.DASH_CMAF_OFFSET_P)}G!==je.None&&G!==je.ActiveLowLatency&&(m=0,this.updateLive())}))}const d=N(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),c=N(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe($(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(N(this.forceEnded$,Ie({allBuffersFull:d,someBufferEnded:c}).pipe(ce(({allBuffersFull:m,someBufferEnded:g})=>m&&g))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add(N(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(m=>{var g;return(g=this.source)===null||g===void 0?void 0:g.addEventListener("sourceopen",m)}));const l=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,g)=>{var S;return Math.max(m,(S=g.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,l),v=this.manifest.representations.video.reduce(h,l);(f||v)&&(this.source.duration=Math.max(f,v)/1e3),this.audioBufferManager&&L(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Re.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=pi(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:_.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new av({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Or.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,r,a;P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.manifestUrlString=Ve(this.manifestUrlString,n,me.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video)),await((r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)))}initBuffer(){P(this.element),this.state$.setState(Re.RUNNING),this.subscription.add(N(...wn.map(e=>I(this.element,e)),I(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(I(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(I(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&Rr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=Kt,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(e=this.stallWatchdogSubscription)===null||e===void 0||e.unsubscribe(),this.stallWatchdogSubscription=pi(Kt).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:_.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){const s={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Rr(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Re.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from-r<=t&&n.to+r>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s)+10;a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class pv{constructor(e,t){this.fov=e,this.orientation=t}}class mv{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,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s: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,s){this.setRotationSpeed(e,t,s),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,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var vv=`#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;}`,gv=`#ifdef GL_ES
39
- precision highp float;precision highp int;
33
+ [best track] ${R==null?void 0:R.quality}
34
+ [selected track] ${A==null?void 0:A.quality}
35
+ `});let N=A&&u&&u.history[A.id]&&gm()-u.history[A.id]<=r.trackCooldown&&(!u.last||A.id!==u.last.id);if(A!=null&&A.id&&u&&!N&&u.recordSelection(A),N&&(u!=null&&u.last)){let k=u.last;return u==null||u.recordSwitch(k),d({message:`
36
+ [last selected] ${k==null?void 0:k.quality}
37
+ `}),k}return u==null||u.recordSwitch(A),A},dt=gw;var Q=i=>new URL(i).hostname;import{assertNever as Em,assertNonNullable as xm,combine as Vw,debounce as _w,ErrorCategory as Pm,filter as Nw,filterChanged as Fw,isNonNullable as Ko,map as es,merge as wm,observableFrom as qw,Subscription as Uw,ValueSubject as Jo,videoQualityToHeight as Hw,videoSizeToQuality as jw}from"@vkontakte/videoplayer-shared";var vm=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"))},ue=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!vm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return vm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ja,isNullable as yw,assertNonNullable as ri}from"@vkontakte/videoplayer-shared";import{isNonNullable as Sm,assertNonNullable as Ka,now as vw}from"@vkontakte/videoplayer-shared";function z(){return vw()}function Yo(i){return z()-i}function Wo(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 ym(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function fr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,f="arraybuffer",h=7e3,b=2e3,v=()=>{if(l)return;Ka(c);let w=Yo(c),U;if(w<b){U=b-w,setTimeout(v,U);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new a,M()},S=w=>(s=w,C),g=w=>(d=w,C),I=()=>(f="json",C),y=()=>{if(!l){if(--u>=0){v(),r&&r();return}l=!0,d&&d(),t&&t()}},E=w=>(p=w,C),M=()=>{c=z(),n=new a,n.open("get",i);let w=0,U,ee=0,k=()=>(Ka(c),Math.max(c,Math.max(U||0,ee||0)));if(s&&n.addEventListener("progress",x=>{let _=z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,U=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(l)return;Ka(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let _=n.response.byteLength-w;_&&s.updateChunk&&s.updateChunk(k(),_)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{Ka(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),C},C={withBitrateReporting:S,withParallel:E,withJSONResponse:I,withRetryCount:w=>(u=w,C),withRetryInterval:(w,U)=>(Sm(w)&&(b=w),Sm(U)&&(h=U),C),withTimeout:w=>(o=w,C),withFinally:g,send:M,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return C}var ei=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 ti=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=z(),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=z()-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=fr(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=z()}_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=z();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 Xa=1e4,Qo=3;var Tw=6e4,Iw=10,Ew=1,xw=500,ii=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 ei(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wo(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=Wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ja(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=()=>{ym(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 ti(Qo,Xa,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},p=(y,E,M)=>{l&&l.abort(),l=fr(this.urlResolver.resolve(y,!1),E,M,()=>this._retryCallback()).withTimeout(Xa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{l=null}).send()},f=(y,E,M)=>{ri(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=y=>{let E=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let M=z()-1e4,R=0;for(let N=0;N<this.bufferStates.length;N++){let $=this.bufferStates[N];y=Math.min(y,$.buf),$.ts<M&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${y} drop=${R} jitter=${this.sourceJitter}`);let A=y-Ew;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?h(1.15):A>1?h(1.1):A>.3?h(1.05):h(1)}},S=y=>{let E,M=()=>E&&E.start?E.start.length:0,R=x=>E.start[x]/1e3,A=x=>E.dur[x]/1e3,N=x=>E.fragIndex+x,$=(x,_)=>({chunkIdx:N(x),startTS:R(x),dur:A(x),discontinuity:_}),C=()=>{let x=0;if(E&&E.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=_;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let X=E.dur.length-1;for(;X>=0&&(Y-=E.dur[X],!(Y<=0));--X);x=Math.min(X,E.dur.length-1-H),x=Math.max(x,0)}return $(x,!0)},w=x=>{let _=M();if(!(_<=0)){if(Ja(x)){for(let H=0;H<_;H++)if(R(H)>x)return $(H)}return C()}},U=x=>{let _=M(),H=x?x.chunkIdx+1:0,Y=H-E.fragIndex;if(!(_<=0)){if(!x||Y<0||Y-_>Iw)return t(`Resync: offset=${Y} bChunks=${_} chunk=`+JSON.stringify(x)),C();if(!(Y>=_))return $(H-E.fragIndex,!1)}},ee=(x,_,H)=>{u&&u.abort(),u=fr(this.urlResolver.resolve(x,!0,this.lowLatency),_,H,()=>this._retryCallback()).withTimeout(Xa).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,_)=>{ee(y,H=>{if(!d())return;E=H;let Y=!!E.lowLatency;Y!==this.lowLatency&&b(Y);let X=0;for(let qe=0;qe<E.dur.length;++qe)X+=E.dur[qe];X>0&&(ri(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,x(w(_))},()=>this._handleNetworkError())},nextChunk:U}},g=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),ri(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:E,logger:M}=this.params,R=S(e.jidxUrl),A,N,$,C,w=0,U,ee,k,x=()=>{U&&(clearTimeout(U),U=void 0);let B=Math.max(xw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=w+B,le=z(),me=Math.min(1e4,te-le);w=le;let tt=()=>{u||d()&&R.seek(()=>{d()&&(w=z(),_(),x())})};me>0?U=window.setTimeout(()=>{this.paused?x():tt()},me):tt()},_=()=>{let B;for(;B=R.nextChunk(C);)C=B,Qi(B);let te=R.nextChunk($);if(te){if($&&te.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?x():(g(),this._initPlayerWith(e));return}qe(te)}else x()},H=(B,te)=>{if(!d()||!this.sourceBuffer)return;let le,me,tt,Yt=rt=>{window.setTimeout(()=>{d()&&H(B,te)},rt)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),Yt(100);else{let rt=z(),vt=E.currentTime;!this.paused&&E.buffered.length>1&&ee===vt&&rt-k>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),ee!==vt&&(ee=vt,k=rt);let Wt=this._getBufferSizeSec();if(Wt>30)M(`Buffered ${Wt} seconds; delaying appendBuffer`),Yt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:rt,buf:Wt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(kr){if(kr.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(le=this.sourceBuffer.buffered.start(0),me=vt,me-le>4&&this.sourceBuffer.remove(le,me-3)),Yt(1e3);else throw kr}}},Y=()=>{N&&A&&(M([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify($)]),H(N,function(){N=null,_()}))},X=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),qe=B=>{d()&&f(X(B),(te,le)=>{if(d()){if(le/=1e3,N=te,$=B,n=B.startTS,le){let me=Math.min(10,B.dur/le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}Y()}},()=>this._handleNetworkError())},Qi=B=>{d()&&(ri(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(B),!1)))},wr=B=>{d()&&(e.cachedHeader=B,H(B,()=>{A=!0,Y()}))};s=!0,R.seek(B=>{if(d()){if(w=z(),!B){x();return}C=B,!yw(y)||B.startTS>y?qe(B):($=B,_())}},y),e.cachedHeader?wr(e.cachedHeader):p(e.headerUrl,wr,()=>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(),Ja(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,ri(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ja(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,f,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(f=this._getBufferSizeSec(),h=d/this.bitrate,f>10&&h>.8||f>15&&h>.5||f>20&&h>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,f)=>{let h=z();if(this.chunkRateEstimator.addInterval(p,h,f)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:h-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Yo(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let f=s.updateChunk(d,p);return f&&u(),f},notifySwitch:d=>{let p=z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=fr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Xa).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;ue(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((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))},Tw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Pw,filter as Tm,fromEvent as ww,interval as kw,isHigher as Aw,isInvariantQuality as Rw,isLower as Lw,merge as $w,Subject as Im,Subscription as Cw}from"@vkontakte/videoplayer-shared";var zo=class{constructor(){this.onDroopedVideoFramesLimit$=new Im;this.subscription=new Cw;this.playing=!1;this.tracks=[];this.forceChecker$=new Im;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Rw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Aw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(ww(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=kw(this.droppedFramesChecker.checkTime).pipe(Tm(()=>this.playing),Tm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Pw(this.droppedFramesChecker.checkTime)),r=$w(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Lw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Za=zo;import{map as Dw,Observable as Mw}from"@vkontakte/videoplayer-shared";import{fromEvent as Ow}from"@vkontakte/videoplayer-shared";var ai=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Bw=(i,e)=>new Mw(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||ai()))},{...r,...e});a.observe(i);let s=Ow(document,"visibilitychange").pipe(Dw(n=>!document.hidden||ai())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Te=Bw;var Gw=["paused","playing","ready"],Yw=["paused","playing","ready"],si=class{constructor(e){this.subscription=new Uw;this.videoState=new L("stopped");this.representations$=new Jo([]);this.textTracksManager=new Se;this.droppedFramesManager=new Za;this.maxSeekBackTime$=new Jo(1/0);this.zeroTime$=new Jo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Pm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let l of n){let u=(t=l.name)!=null?t:l.index.toString(10),c=(r=lt(l.name))!=null?r:jw(l.video),d=l.bitrate/1e3,p={...l.video};if(!c)continue;let f={id:u,quality:c,bitrate:d,size:p};o.push({track:f,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:l})=>l===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ko(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Yw.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&Gw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(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==null?void 0: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(J(this.params.source.url,l))}return;default:return Em(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Pm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};wm(this.videoState.stateChangeStarted$.pipe(es(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(es(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ae(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(Q(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=oe(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(es(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Fw(),es(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(Vw({zeroTime:this.zeroTime$.pipe(Nw(Ko)),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(ne(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ve(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(Te(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&Hw(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Em(a.to)}},t)).add(wm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,qw(["init"])).pipe(_w(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),se(this.video)}createLiveDashPlayer(){let e=new ii({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var u,c,d,p,f,h;let e=this.representations$.getValue(),t=(c=(u=this.params.desiredState.videoTrack.getTransition())==null?void 0:u.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ko(t)?t:dt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(f=this.params.desiredState.videoTrack.getState())==null?void 0:f.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let b=(h=e.find(({track:v})=>v.id===s))==null?void 0:h.representation;xm(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;xm(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(J(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var km=si;var pt=(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 dA,assertNonNullable as qb,debounce as pA,ErrorCategory as yu,filter as hA,filterChanged as Ub,fromEvent as fA,isLowerOrEqual as Hb,isNonNullable as mA,videoSizeToQuality as jb,map as Tu,merge as hs,observableFrom as bA,observeElementSize as gA,once as vA,Subscription as SA,ValueSubject as Gb}from"@vkontakte/videoplayer-shared";var ts=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}},mr=class extends ts{constructor(){super(),this.listeners||ts.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)}},ni=class{constructor(){Object.defineProperty(this,"signal",{value:new mr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ni.prototype[Symbol.toStringTag]="AbortController",mr.prototype[Symbol.toStringTag]="AbortSignal");function rs(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 Xo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!rs({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 p=new t(u,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(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(f){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((f,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var oi=rs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Am=oi?Xo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=oi?Am.fetch:window.fetch,w0=oi?Am.Request:window.Request,ze=oi?ni:window.AbortController,k0=oi?mr:window.AbortSignal;var _b=Oe(Da(),1);var ui=(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 gu,assertNonNullable as qt,combine as Db,ErrorCategory as ft,filter as us,filterChanged as aA,fromEvent as Ir,interval as vu,isNonNullable as Mb,map as Su,merge as Er,Subject as Ob,Subscription as Bb,tap as sA,throttle as nA,ValueSubject as he}from"@vkontakte/videoplayer-shared";var Tr=Oe(Qa(),1);var Ww=(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)},Qw=i=>window.clearTimeout(i),Rm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Zo=Rm?Ww:window.requestIdleCallback,L0=Rm?Qw:window.cancelIdleCallback;var xb=Oe(Ga(),1);import{assertNever as zw,CurrentClientBrowser as Kw,ErrorCategory as Lm,getCurrentBrowser as Jw,Subject as $m}from"@vkontakte/videoplayer-shared";var Xw=16,Mm=!1,Cm,Dm;try{Mm=Jw().browser===Kw.Safari&&parseInt((Dm=(Cm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Cm[1])!=null?Dm:"",10)<=Xw}catch(i){console.error(i)}var eu=class{constructor(e){this.bufferFull$=new $m;this.error$=new $m;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Lm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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;Mm&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Lm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:zw(t)}}},Om=eu;var tu=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 Sr,assertNever as Kk,assertNonNullable as Ke,ErrorCategory as yr,fromEvent as pu,getExponentialDelay as hu,once as Jk,isNonNullable as Eb,isNullable as Je,Subject as Xk,Subscription as Zk,ValueSubject as Li}from"@vkontakte/videoplayer-shared";var V=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 br=class extends V{};var li=class extends V{};var ci=class extends V{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 di=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends V{constructor(t,r){super(t,r);this.data=this.content}};var j=class extends V{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Mt=class extends j{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 fi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends j{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 gi=class extends j{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var vi=class extends j{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Si=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends j{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 Ti=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends j{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var xi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends j{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 wi=class extends j{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 ki=class extends j{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 ek={ftyp:ci,moov:di,moof:pi,mdat:hi,sidx:Mt,trak:fi,mdia:Si,mfhd:Ei,tkhd:yi,traf:xi,tfhd:Pi,tfdt:wi,trun:ki,minf:Ti,sv3d:mi,st3d:bi,prhd:gi,proj:Ii,equi:vi,uuid:li,unknown:br},Ot=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(a){break}return t}createBox(e,t){let r=ek[e];return r?new r(t,new i):new br(t,new i)}};var gr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var rk=new TextDecoder("ascii"),ik=i=>rk.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",ak=i=>{let e=new Mt(i,new Ot),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})},sk=(i,e)=>{let r=new Ot().parse(i),a=new gr(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)},nk=(i,e)=>{let r=new Ot().parse(i),s=new gr(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,p)=>d+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},ok=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 Ot().parse(i),a=new gr(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},Bm={validateData:ik,parseInit:ok,getIndexRange:()=>{},parseSegments:ak,parseFeedableSegmentChunk:sk,getSegmentEndTime:nk};import{assertNonNullable as iu,isNonNullable as Fm,isNullable as lk}from"@vkontakte/videoplayer-shared";import{assertNever as uk}from"@vkontakte/videoplayer-shared";var Vm={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"}},_m=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=Ai(i,t),a=r in Vm,s=a?Vm[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=Ai(l),d=u*2**((o-1)*8)+c,p=t+o,f;return p+d>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:f,valueSize:d}},Ai=(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},$e=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ai(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:uk(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=_m(r);if(!e(a))return;a.type==="master"&&Bt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Nm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=_m(i);return Bt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=$e(o,n):s===17026?t=$e(o,n):s===17029&&(r=$e(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var qm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ck=[231,22612,22743,167,171,163,160,175],dk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Bt(i,({tag:p,type:f,value:h,valueSize:b})=>{if(p===21419){let v=$e(h,f);u=Ai(v)}else p!==21420&&(u=void 0);return p===408125543?(e=h.byteOffset,t=h.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=$e(h,f):p===17545?a=$e(h,f):p===21420&&u===475249515?l=$e(h,f):p===374648427?Bt(h,({tag:v,type:S,value:g})=>v===30321?(c=$e(g,S)===1,!1):!0):s&&n&&qm.includes(p)&&(o=!0),!o}),iu(e,"Failed to parse webm Segment start"),iu(t,"Failed to parse webm Segment end"),iu(a,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pk=i=>{if(lk(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hk=(i,e)=>{let t=!1,r=!1,a=o=>Fm(o.time)&&Fm(o.position),s=[],n;return Bt(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=$e(u,l));break;case 183:break;case 241:n&&(n.position=$e(u,l));break;default:t&&qm.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}}})},fk=i=>{let e=0,t=!1;try{Bt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ck.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Um={validateData:Nm,parseInit:dk,getIndexRange:pk,parseSegments:hk,parseFeedableSegmentChunk:fk};var uu=Oe(pb(),1);import{isNonNullable as fb,isNullable as mb}from"@vkontakte/videoplayer-shared";var hb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var bb=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==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Vt=(i,e)=>{let t=i;t=(0,uu.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,uu.default)(t,n,(o,l)=>mb(s)?o:mb(l)?s:s.padStart(parseInt(l,10),"0"))}return t},vb=(i,e)=>{var y,E,M,R,A,N,$,C,w,U,ee,k,x,_,H,Y,X,qe,Qi,wr,B,te,le,me,tt,Yt,rt,vt,Wt,kr,Vu,_u,Nu,Fu,qu,Uu,Hu,ju,Gu,Yu,Wu,Qu;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(M=(E=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:E.trim())!=null?M:"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),h=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=bb(f);else if(h){let be=bb(h);fb(be)&&(p=be)}else v&&(p=parseInt(v,10));let S=0,g=(A=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?A:[],I=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let be of l){let zi=be.getAttribute("mimeType"),Wg=be.getAttribute("codecs"),zu=(N=be.getAttribute("contentType"))!=null?N:zi==null?void 0:zi.split("/")[0],Qg=(C=($=be.getAttribute("profiles"))==null?void 0:$.split(","))!=null?C:[],Ku=be.querySelectorAll("Representation"),zg=be.querySelector("SegmentTemplate");if(zu==="text"){for(let G of Ku){let it=G.getAttribute("id")||"",Ki=be.getAttribute("lang"),Qt=be.getAttribute("label"),Ms=(ee=(U=(w=G.querySelector("BaseURL"))==null?void 0:w.textContent)==null?void 0:U.trim())!=null?ee:"",Os=new URL(Ms||o,e).toString(),Ji=it.includes("_auto");a.text.push({id:it,lang:Ki,label:Qt,isAuto:Ji,kind:"text",url:Os})}continue}for(let G of Ku){let it=(k=G.getAttribute("mimeType"))!=null?k:zi,Ki=(_=(x=G.getAttribute("codecs"))!=null?x:Wg)!=null?_:"",Qt=(Y=(H=G.getAttribute("contentType"))!=null?H:it==null?void 0:it.split("/")[0])!=null?Y:zu,Ms=(qe=(X=be.getAttribute("profiles"))==null?void 0:X.split(","))!=null?qe:[],Os=parseInt((Qi=G.getAttribute("width"))!=null?Qi:"",10),Ji=parseInt((wr=G.getAttribute("height"))!=null?wr:"",10),Ju=parseInt((B=G.getAttribute("bandwidth"))!=null?B:"",10)/1e3,Xu=(te=G.getAttribute("frameRate"))!=null?te:"",Kg=(le=G.getAttribute("quality"))!=null?le:void 0,Jg=Xu?hb(Xu):void 0,Xg=(me=G.getAttribute("id"))!=null?me:(S++).toString(10),Zg=Qt==="video"?`${Ji}p`:Qt==="audio"?`${Ju}Kbps`:Ki,ev=`${Xg}@${Zg}`,tv=(rt=(Yt=(tt=G.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:Yt.trim())!=null?rt:"",Zu=new URL(tv||o,e).toString(),rv=[...g,...Qg,...Ms],Bs,iv=G.querySelector("SegmentBase"),St=(vt=G.querySelector("SegmentTemplate"))!=null?vt:zg;if(iv){let yt=(kr=(Wt=G.querySelector("SegmentBase Initialization"))==null?void 0:Wt.getAttribute("range"))!=null?kr:"",[Tt,_s]=yt.split("-").map(zt=>parseInt(zt,10)),at={from:Tt,to:_s},Ar=(Vu=G.querySelector("SegmentBase"))==null?void 0:Vu.getAttribute("indexRange"),[Ns,Xi]=Ar?Ar.split("-").map(zt=>parseInt(zt,10)):[],Rr=Ar?{from:Ns,to:Xi}:void 0;Bs={type:"byteRange",url:Zu,initRange:at,indexRange:Rr}}else if(St){let yt={representationId:(_u=G.getAttribute("id"))!=null?_u:void 0,bandwidth:(Nu=G.getAttribute("bandwidth"))!=null?Nu:void 0},Tt=parseInt((Fu=St.getAttribute("timescale"))!=null?Fu:"",10),_s=(qu=St.getAttribute("initialization"))!=null?qu:"",at=St.getAttribute("media"),Ar=(Hu=parseInt((Uu=St.getAttribute("startNumber"))!=null?Uu:"",10))!=null?Hu:1,Ns=Vt(_s,yt);if(!at)throw new ReferenceError("No media attribute in SegmentTemplate");let Xi=(ju=St.querySelectorAll("SegmentTimeline S"))!=null?ju:[],Rr=[],zt=0,Fs="",qs=0;if(Xi.length){let Zi=Ar,Pe=0;for(let Kt of Xi){let Me=parseInt((Gu=Kt.getAttribute("d"))!=null?Gu:"",10),It=parseInt((Yu=Kt.getAttribute("r"))!=null?Yu:"",10)||0,ea=parseInt((Wu=Kt.getAttribute("t"))!=null?Wu:"",10);Pe=Number.isFinite(ea)?ea:Pe;let Us=Me/Tt*1e3,Hs=Pe/Tt*1e3;for(let ta=0;ta<It+1;ta++){let sv=Vt(at,{...yt,segmentNumber:Zi.toString(10),segmentTime:(Pe+ta*Me).toString(10)}),el=(Hs!=null?Hs:0)+ta*Us,nv=el+Us;Zi++,Rr.push({time:{from:el,to:nv},url:sv})}Pe+=(It+1)*Me,zt+=(It+1)*Us}qs=Pe/Tt*1e3,Fs=Vt(at,{...yt,segmentNumber:Zi.toString(10),segmentTime:Pe.toString(10)})}else if(fb(p)){let Pe=parseInt((Qu=St.getAttribute("duration"))!=null?Qu:"",10)/Tt*1e3,Kt=Math.ceil(p/Pe),Me=0;for(let It=1;It<Kt;It++){let ea=Vt(at,{...yt,segmentNumber:It.toString(10),segmentTime:Me.toString(10)});Rr.push({time:{from:Me,to:Me+Pe},url:ea}),Me+=Pe}qs=Me,Fs=Vt(at,{...yt,segmentNumber:Kt.toString(10),segmentTime:Me.toString(10)})}let av={time:{from:qs,to:1/0},url:Fs};Bs={type:"template",baseUrl:Zu,segmentTemplateUrl:at,initUrl:Ns,totalSegmentsDurationMs:zt,segments:Rr,nextSegmentBeyondManifest:av,timescale:Tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!it)continue;let Vs={video:"video",audio:"audio",text:"text"}[Qt];Vs&&a[Vs].push({id:ev,kind:Vs,segmentReference:Bs,profiles:rv,duration:p,bitrate:Ju,mime:it,codecs:Ki,width:Os,height:Ji,fps:Jg,quality:Kg})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,container:I,representations:a}};var cu=Oe(Qa(),1);import{videoSizeToQuality as zk}from"@vkontakte/videoplayer-shared";var Sb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?lt(s):void 0)!=null?o:zk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},yb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Tb=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,cu.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,cu.default)(i,-1)},Ib=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),du=i=>"url"in i,_t=i=>i.type==="template",Ri=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var $i=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new Xk;this.gaps=[];this.subscription=new Zk;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=Sr(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 Om(this.sourceBuffer),this.subscription.add(pu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:yr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(pu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yr.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,tu(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=Sr(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();Eb(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=Sr(this.destroyAbortController.signal,async function*(e){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let l of this.representations.keys()){let u=e.find(p=>p.id===l);u&&this.representations.set(l,u);let c=this.representations.get(l);if(!c||!_t(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,r=this.representations.get(t);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!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=Bm;break;case"webm":this.containerParser=Um;break;default:Kk(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()){var u,c;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(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((u=a==null?void 0:a.time.to)!=null?u:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=pt(this.sourceBuffer.buffered,e),f=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=f)}if(isFinite(this.bufferLimit)&&tu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=pt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,Tr.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&pt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Tr.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;Eb(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!_t(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),l=(r=this.segments.get(n.id))!=null?r:[],u=(s=(a=(0,Tr.default)(l,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(u)>=Math.floor(d.time.from)&&Math.floor(u)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...l,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!_t(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Vt(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],l=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));l&&(l.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(l=>l.time.from<=e&&l.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:f}},h)=>{let b=p<=r&&f>=r,v=p>r||b||h===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=r+S||f<=r+S;return(d==="none"||d==="partially_ejected"&&v&&g&&this.sourceBuffer&&!ui(this.sourceBuffer.buffered,r))&&v&&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 p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);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 Sr(o,async function*(){let c=hu(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 p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}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]),Ri(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 Sr(n,async function*(){let l=hu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),pu(window,"online").pipe(Jk()).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),Ri(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(_t(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Tr.default)(e,0).byte.from,to:(0,Tr.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:yr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!_t(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:yr.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!=null&&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,p=l==="byteRange",f=p?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,v=p?d.byte.to-r:e.byteLength,S=b<a,g=v<=a;if(d.status==="downloading"&&S&&g){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+b,f);this.sourceBufferTaskQueue.append(I,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(f,a-b),c.loadedBytes>c.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===f?I:this.containerParser.parseFeedableSegmentChunk(I);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(E=>{if(s.aborted)n();else if(E)c.fedBytes+=y.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",du(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Zo(()=>(0,xb.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?Sr(this.destroyAbortController.signal,async function*(){let o=hu(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 p=c;this.isLive&&_t(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),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:yr.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=>{var d;s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=du(u)?(d=u.size)!=null?d: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 p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let 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=Zo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:yr.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 Ci=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Pb=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};import{abortable as Di,assertNever as wb,fromEvent as kb,merge as eA,now as fu,Subscription as tA,ValueSubject as mu}from"@vkontakte/videoplayer-shared";var is=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new mu(void 0);this.lastConnectionReused$=new mu(void 0);this.lastRequestFirstBytes$=new mu(void 0);this.abortAllController=new ze;this.subscription=new tA;this.fetchManifest=Di(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ci(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(Mi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Di(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}={}){var A,N;let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let $=new URL(u,location.href);$.searchParams.append("bytes",`${r.from}-${r.to}`),u=$.toString();break}default:wb(t)}this.requestQuic&&(u=Ci(u));let d=this.abortAllController.signal,p;if(n){let $=new ze;if(p=eA(kb(this.abortAllController.signal,"abort"),kb(n,"abort")).subscribe(()=>{try{$.abort()}catch(C){Mi(C)}}),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(C){Mi(C)}d=$.signal}let f=fu(),h=yield Qe(u,{priority:s,headers:c,signal:d}).catch(Mi),b=fu();if(!h)return p==null||p.unsubscribe(),null;if((A=this.throughputEstimator)==null||A.addRawRtt(b-f),!h.ok||!h.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${h.status}: ${h.statusText}`));if(this.onHeadersReceived(h.headers),!a&&!o)return p==null||p.unsubscribe(),h.arrayBuffer();let[v,S]=h.body.tee(),g=v.getReader();o&&((N=this.throughputEstimator)==null||N.trackStream(S,l));let I=0,y=new Uint8Array(0),E=!1,M=$=>{p==null||p.unsubscribe(),E=!0,Mi($)},R=Di(d,async function*({done:$,value:C}){if(I===0&&this.lastRequestFirstBytes$.next(fu()-f),d.aborted){p==null||p.unsubscribe();return}if(!$&&C){let w=new Uint8Array(y.length+C.length);w.set(y),w.set(C,y.length),y=w,I+=C.byteLength,a==null||a(new DataView(y.buffer),I),yield g==null?void 0:g.read().then(R,M)}}.bind(this));return yield g==null?void 0:g.read().then(R,M),p==null||p.unsubscribe(),E?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=Di(this.abortAllController.signal,async function*(e,t,r){var S;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 p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let f=t.parseInit(p),h=(S=e.indexRange)!=null?S:t.getIndexRange(f);if(!h)throw new ReferenceError("No way to load representation index");let b;if(l)b=new DataView(d,h.from-n,h.to-h.from+1);else{let g=yield this.fetch(e.url,{range:h,priority:r,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,f,h);return{init:f,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=Di(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}=Pb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:wb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Mi=i=>{if(!Ri(i))throw i};var Nt=(i,e,t)=>t*e+(1-t)*i,bu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Ab=(i,e,t,r)=>{let a=0,s=t,n=bu(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 rA,ValueSubject as Rb}from"@vkontakte/videoplayer-shared";var ht=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Rb(e.initial),this.debounced$=new Rb(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Z(`raw_${t}`),this.smoothedSeries$=new Z(`smoothed_${t}`),this.reportedSeries$=new Z(`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)&&(rA(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 as=class extends ht{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Nt(this.slow,t,this.params.emaAlphaSlow),this.fast=Nt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var ss=class extends ht{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=bu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Nt(this.emaSmoothed,t,this.params.emaAlpha);let a=Ab(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var ns=class extends ht{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?Nt(this.smoothed,t,this.params.emaAlpha):t}};var Ft=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new as({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ss({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 ns({initial:e,label:"liveEdgeDelay",...t})}};var Lb=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Xe=()=>window.ManagedMediaSource||window.MediaSource,os=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},$b=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Cb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Vb=["timeupdate","progress","play","seeked","stalled","waiting"];var ls=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Bb;this.representationSubscription=new Bb;this.state$=new L("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Ob;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.isLive$=new he(!1);this.liveDuration$=new he(0);this.liveAvailabilityStartTime$=new he(void 0);this.bufferLength$=new he(0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Ob;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=gu(this.destroyController.signal,async function*(e,t,r){var a;this.element=e,this.manifestUrlString=J(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=gu(this.destroyController.signal,async function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ft.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=vb(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:ft.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var l,u,c,d;return!!((u=(l=this.element)==null?void 0:l.canPlayType)!=null&&u.call(l,n)&&((d=(c=Xe())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:(0,_b.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))}}.bind(this));this.initRepresentations=gu(this.destroyController.signal,async function*(e,t,r){var f;qt(this.manifest),qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add(Ir(h,"error").pipe(us(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?Cb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&os())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $i("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Mb(t)&&(this.audioBufferManager=new $i("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(vu(1e3).subscribe(h=>{var b;if((b=this.element)!=null&&b.paused){let v=Mo(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add(Er(...Vb.filter(h=>h!=="waiting").map(h=>Ir(this.element,h))).pipe(Su(h=>this.element?pt(this.element.buffered,this.element.currentTime*1e3):0),aA(),us(h=>!!h),sA(h=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(us(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=b-v,y=1+Math.sign(I)*g;Math.abs(I)<S?y=1:Math.abs(I)>S*2&&(y=1+Math.sign(I)*g*2),Lb(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,g;let v=0;if(b){let I=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(E=>{var M,R;return(R=(M=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:M.to)!=null?R:I}))-I}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let h=0;this.representationSubscription.add(Db({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(nA(1e3)).subscribe(async({liveLoadBufferLength:b,bufferLength:v})=>{if(qt(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,g=Mo(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,R=this.isActiveLowLatency?v:b,A=3;if(this.isActiveLowLatency?A=0:R<y+M&&R>=y?A=1:g!==0&&R<y&&(A=2),isFinite(b)&&(h=b>h?b:h),A===2||A===1){let N=h-(y+E),$=this.normolizeLiveOffset(Math.trunc(g+N/S)),C=Math.abs($-g),w;!b||C<=this.tuning.dashCmafLive.offsetCalculationError?w=g:$>0&&C>this.tuning.dashCmafLive.offsetCalculationError?w=$:w=0,this.manifestUrlString=J(this.manifestUrlString,w,2)}A!==3&&A!==0&&(h=0,this.updateLive())}))}let o=Er(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Su(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),l=Er(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Su(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(Er(this.forceEnded$,Db({allBuffersFull:o,someBufferEnded:l}).pipe(us(({allBuffersFull:h,someBufferEnded:b})=>h&&b))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(h=this.source)==null||h.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(Er(...this.bufferManagers.map(h=>h.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(h=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",h)}));let u=(f=this.manifest.duration)!=null?f:0,c=(h,b)=>{var v;return Math.max(h,(v=b.duration)!=null?v:0)},d=this.manifest.representations.audio.reduce(c,u),p=this.manifest.representations.video.reduce(c,u);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&Mb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=vu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:ft.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new is({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ft.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,a,s,n;qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=J(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio)))}initBuffer(){qt(this.element),this.state$.setState("running"),this.subscription.add(Er(...Vb.map(e=>Ir(this.element,e)),Ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ir(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ui(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=vu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ft.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)}seek(e,t){var a,s,n,o,l;qt(this.element),qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),ui(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var ds=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...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 Nb=`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 Fb=`#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 Sv{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new pv(this.params.fov,this.params.orientation),this.cameraRotationManager=new mv(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"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),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(s,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(r,0),this.gl.uniform2f(a,-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(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(vv,this.gl.VERTEX_SHADER),s=this.createShader(gv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),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,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),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,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,u=t-r,d=e+s,c=t+r,l=e-s,h=t+r;return[a,n,o,u,d,c,l,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(){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 Yo{constructor(e){this.subscription=new ie,this.videoState=new ue(ne.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new mt,this.droppedFramesManager=new _o,this.videoTracks$=new y([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new cp,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==ne.STOPPED&&n!==p.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(u.position-c,u.forcePrecise)}if(n===p.STOPPED){a!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case ne.STOPPED:this.videoState.startTransitionTo(ne.READY),this.prepare();return;case ne.READY:n===p.PAUSED?(this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case ne.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ne.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()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new Sv(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.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 n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(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(Je(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new fv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=Ot(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:_.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe($(d=>d.map(({track:c})=>c)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ce(L),Te()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ai(this.video,t.isLooped,r)),this.subscription.add(Ct(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ai(this.video,t.playbackRate,s.playbackRateState$,r)),a(Sd(this.video),this.elementSize$),a(ni(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var c;if(d===Re.MANIFEST_READY){const l=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),v=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=tv(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of v){const E=ev(S);if(E){l.push({track:E,representation:S});const A=!this.params.tuning.isAudioDisabled&&iv(f,v,S);A&&this.audioRepresentations.set(S.id,A)}}this.videoTracks$.next(l);for(const S of m){const E=sv(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(l.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();P(g),this.player.initRepresentations(g.id,(c=this.audioRepresentations.get(g.id))===null||c===void 0?void 0:c.id,this.params.sourceHls)}else d===Re.REPRESENTATIOS_READY&&(this.videoState.setState(ne.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:_.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(N(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$,I(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!==Re.RUNNING||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),v=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(l){let m=l.id;!this.params.output.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=kt(S),A=kt(l);if(E&&A)return ts(E,A)&&ts(E,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(Se.VIDEO,m).catch(n);const g=this.audioRepresentations.get(l.id);g&&this.player.switchRepresentation(Se.AUDIO,g.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(he(),$(d=>{var c;return d&&((c=this.videoTracks$.getValue().find(({representation:{id:l}})=>l===d))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var c,l;if(d!=null&&d.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===p.READY),he());this.subscription.add(N(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(N(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ke(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,l=this.params.output.currentVideoTrack$.getValue(),h=mi(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(c&&!u&&(r=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,l&&(n=(a=this.audioRepresentations.get(l.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),g=bs(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:v,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=u?g!=null?g:c:c!=null?c:g;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Mt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ne.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.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),It(this.video)}}class bv extends Yo{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class yv extends Yo{constructor(e){super(e),this.liveOffset=new Zr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ie({interval:pi(Kt),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===ne.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ie({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===ne.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const Ne={};var W;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const zt=(i,e)=>new Br(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class Tv{constructor(e){this.subscription=new ie,this.videoState=new ue(W.INITIALIZING),this.textTracksManager=new mt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==W.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case W.STOPPED:break;case W.READY:case W.PLAYING:case W.PAUSED:this.stop();break;default:U(t)}break;case p.READY:switch(t){case W.STOPPED:this.prepare();break;case W.READY:case W.PLAYING:case W.PAUSED:break;default:U(t)}break;case p.PLAYING:switch(t){case W.PLAYING:break;case W.STOPPED:this.prepare();break;case W.READY:case W.PAUSED:this.playIfAllowed();break;default:U(t)}break;case p.PAUSED:switch(t){case W.PAUSED:break;case W.STOPPED:this.prepare();break;case W.READY:this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case W.PLAYING:this.pause();break;default:U(t)}break;default:U(s)}},this.video=Rt(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(Je(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),It(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(Ne.Hls=r.default,Ne.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){P(Ne.Hls,"hls.js not loaded"),this.hls=new Ne.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){P(Ne.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Ot(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ai(this.video,e.isLooped,s)),this.subscription.add(Ct(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ai(this.video,e.playbackRate,r.playbackRateState$,s)),a(ni(this.video),t.elementVisible$),this.subscription.add(zt(this.hls,Ne.Events.ERROR).subscribe(d=>{var c;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:_.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(c=d.err)===null||c===void 0?void 0:c.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},s)),a(zt(this.hls,Ne.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((c,l)=>{var h,f;const v=l.name||l.height.toString(10),{width:m,height:g}=l,S=(f=Ss((h=l.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:kt({width:m,height:g});if(!S)return c;const E=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,A={id:v.toString(),quality:S,bitrate:l.bitrate/1e3,size:{width:m,height:g},fps:E};return this.trackLevels.set(v,{track:A,level:l}),c.push(A),c},[]))),t.availableVideoTracks$),a(zt(this.hls,Ne.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const c=[];for(const l of d.subtitleTracks){const h=l.name,f=l.attrs.URI||"",v=l.lang,m="internal";c.push({id:h,url:f,language:v,type:m})}e.internalTextTracks.startTransitionTo(c)}}),a(zt(this.hls,Ne.Events.LEVEL_LOADING).pipe($(({url:d})=>Je(d))),t.hostname$),a(zt(this.hls,Ne.Events.FRAG_CHANGED),d=>{var c,l,h,f;const{video:v,audio:m}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((c=v==null?void 0:v.endPTS)!==null&&c!==void 0?c:0)-((l=v==null?void 0:v.startPTS)!==null&&l!==void 0?l:0))*1e3),t.currentAudioSegmentLength$.next((((h=m==null?void 0:m.endPTS)!==null&&h!==void 0?h:0)-((f=m==null?void 0:m.startPTS)!==null&&f!==void 0?f:0))*1e3)}),this.subscription.add(tt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:l})=>l===d))===null||c===void 0?void 0:c.track},o=zt(this.hls,Ne.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(ce(L)).subscribe(t.currentVideoTrack$,s),this.subscription.add(tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var c;if(Q(d))return;const l=(c=this.trackLevels.get(d.id))===null||c===void 0?void 0:c.level;if(!l)return;const h=this.hls.levels.indexOf(l),f=this.hls.currentLevel,v=this.hls.levels[f];!v||l.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=N(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ke(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(W.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(W.PLAYING),await Mt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:t}))||(this.videoState.setState(W.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(W.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(W.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const kn="X-Playback-Duration";var Pn=async i=>{var e;const t=await bi(i),s=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(kn)?parseInt(t.headers.get(kn),10):void 0};const Ev=i=>{let e=null;if(i.QUALITY&&(e=Ss(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kt({width:t,height:s})}return e!=null?e:null},$v=(i,e)=>{var t,s;const r=i.split(`
46
- `),a=[],n=[];for(let o=0;o<r.length;o++){const u=r[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!c)){if(d){const l=as(d[1].split(",").map(E=>E.split("="))),h=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,f=Ev(l);let v;l.BANDWIDTH&&(v=parseInt(l.BANDWIDTH,10)/1e3||void 0),!v&&l["AVERAGE-BANDWIDTH"]&&(v=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let g;if(l.RESOLUTION){const[E,A]=l.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&A&&(g={width:E,height:A})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:v,size:g,fps:m})}if(c){const l=as(c[1].split(",").map(m=>m.split("=")).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(s=l.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=l.LANGUAGE,v=l.NAME;h&&f&&n.push({type:"internal",id:f,label:v,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},Av=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let or=0;const aa=async(i,e=i,t)=>{const r=await(await bi(i)).text();or+=1;try{const{qualityManifests:a,textTracks:n}=$v(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(or<=t.manifestRetryMaxCount)return await Av(Qi(or-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),aa(i,e,t)}return{qualityManifests:[],textTracks:[]}};var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ee||(ee={}));class wv{constructor(e){var t;this.subscription=new ie,this.videoState=new ue(ee.STOPPED),this.textTracksManager=new mt,this.manifests$=new y([]),this.liveOffset=new Zr,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),l.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&l.state===Y.Requested){this.videoState.startTransitionTo(ee.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ee.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ee.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ee.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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ee.CHANGING_MANIFEST:break;default:return U(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pe.INVARIANT,url:this.params.source.url},aa(Ve(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:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(Je(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const l=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),c.find(h=>h.id===l)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ai(this.video,t.playbackRate,r.playbackRateState$,s)),a(ni(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&L(d.to)){const l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Je(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===ee.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const c=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(c||void 0)},s)),this.subscription.add(Ie({startTime:this.manifestStartTime$.pipe(ce(L)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,s));const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oe(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:c}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[l,h]of[[d,"mq"],[c,"lq"]]){const f=String(parseFloat(l||""));h&&l&&n.searchParams.set(h,f)}}const o=this.params.format===b.HLS_LIVE_CMAF?me.DASH_CMAF_OFFSET_P:me.OFFSET_P,u=Ve(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),Pn(u).then(d=>{var c;if(!Q(d))this.maxSeekBackTime$.next(d);else{const l=(c=this.params.source.maxSeekBackTime)!==null&&c!==void 0?c:this.maxSeekBackTime$.getValue();if(Q(l)||!isFinite(l))try{bi(u).then(h=>h.text()).then(h=>{var f;const v=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(v){const m=new URL(v,u).toString();Pn(m).then(g=>{Q(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class kv{constructor(e){this.subscription=new ie,this.videoState=new ue(re.STOPPED),this.textTracksManager=new mt,this.manifests$=new y([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==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),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n||o||u){const l=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&c.state===Y.Requested&&this.seek(c.position),s){case re.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return U(s)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pe.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(Je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),aa(Ve(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:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const l=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),c.find(h=>h.id===l)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:_.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ai(this.video,t.isLooped,s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ai(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&L(c.to)){const h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(v=>v.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Je(f.url));const v=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(v!==m){const g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(v),g.playbackRate=v)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===Y.Requested&&this.seek(u.position)},s))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,s)),!bd()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(N(I(o,"addtrack"),I(o,"removetrack"),I(o,"change"),Oe(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},s))}const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oe(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,c]of[[o,"mq"],[u,"lq"]]){const l=String(parseFloat(d||""));c&&d&&n.searchParams.set(c,l)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var le;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(le||(le={}));class Pv{constructor(e){this.subscription=new ie,this.videoState=new ue(le.STOPPED),this.trackUrls={},this.textTracksManager=new mt,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==le.STOPPED&&(this.videoState.startTransitionTo(le.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(le.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(d&&a!==le.READY&&!c){this.handleQualityLimitTransition(d.to.max);return}if(a===le.STOPPED){this.videoState.startTransitionTo(le.READY),this.prepare();return}if(c){const{currentTime:h}=this.video;this.prepare(),l.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[c.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&l.state===Y.Requested&&this.seek(l.position),a){case le.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(le.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed());return;case le.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),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,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ot(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ai(this.video,t.isLooped,s)),this.subscription.add(Ct(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ai(this.video,t.playbackRate,r.playbackRateState$,s)),a(ni(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,u;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===le.READY&&this.videoState.setState(le.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&L(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const c=this.params.desiredState.playbackRate.getState(),l=(u=this.params.output.element$.getValue())===null||u===void 0?void 0:u.playbackRate;if(c!==l){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ke(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),It(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;P(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];P(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Cr(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Je(s))}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(s=Object.values(this.trackUrls).find(l=>!Pt(l.track.quality)&&ts(l.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,c=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&c&&br(c.quality,u.quality)&&(n=u),!n){const l=Object.values(this.trackUrls).filter(f=>!Pt(f.track.quality)&&Zt(f.track.quality,e)),h=l.length;h&&(n=l[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=bs(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const Ln=["stun:videostun.mycdn.me:80"],Lv=1e3,Dv=3,dr=()=>null;class xv{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=dr,this.externalStopCallback=dr,this.externalErrorCallback=dr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.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:Ln}]};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:_.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Lv)}normalizeOptions(e={}){const t={stunServerList:Ln,maxRetryNumber:Dv,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var te;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(te||(te={}));class _v{constructor(e){this.videoState=new ue(te.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case te.READY:s===p.PAUSED?(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case te.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new xv(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),It(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};N(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Ot(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ni(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===te.READY&&this.videoState.setState(te.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ct(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case te.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case te.READY:break;case te.PAUSED:t.playbackState.setState(p.PAUSED);break;case te.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return U(n.to)}},s)).add(N(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ke(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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(Je(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:Pe.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(te.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:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Mt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Dn{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 $e;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg",i.DASH_ANY_MPEG="dash_any_mpeg",i.DASH_ANY_WEBM="dash_any_webm",i.DASH_SEP="dash_sep"})($e||($e={}));var ft;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(ft||(ft={}));var lr,ur,cr,hr,Hi,fr,Gi,pr,Yi,mr,qi,vr,ji,gr,Wi,Sr;const qo=Mr().device===yd.Android,pt=document.createElement("video"),Rv='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Iv='video/mp4; codecs="hev1.1.6.L93.B0"',jo='video/webm; codecs="vp09.00.10.08"',Wo='video/webm; codecs="av01.0.00M.08"',Cv='audio/mp4; codecs="mp4a.40.2"',Ov='audio/webm; codecs="opus"',Et={mms:Go(),mse:cv(),hls:!!(!((lr=pt.canPlayType)===null||lr===void 0)&&lr.call(pt,"application/x-mpegurl")||!((ur=pt.canPlayType)===null||ur===void 0)&&ur.call(pt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},_e={mp4:!!(!((cr=pt.canPlayType)===null||cr===void 0)&&cr.call(pt,"video/mp4")),webm:!!(!((hr=pt.canPlayType)===null||hr===void 0)&&hr.call(pt,"video/webm")),cmaf:!0},Qe={h264:!!(!((fr=(Hi=Tt())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||fr===void 0)&&fr.call(Hi,Rv)),h265:!!(!((pr=(Gi=Tt())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||pr===void 0)&&pr.call(Gi,Iv)),vp9:!!(!((mr=(Yi=Tt())===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||mr===void 0)&&mr.call(Yi,jo)),av1:!!(!((vr=(qi=Tt())===null||qi===void 0?void 0:qi.isTypeSupported)===null||vr===void 0)&&vr.call(qi,Wo)),aac:!!(!((gr=(ji=Tt())===null||ji===void 0?void 0:ji.isTypeSupported)===null||gr===void 0)&&gr.call(ji,Cv)),opus:!!(!((Sr=(Wi=Tt())===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||Sr===void 0)&&Sr.call(Wi,Ov))},fi=(Qe.h264||Qe.h265)&&Qe.aac;let $t;const Mv=async()=>{if(!window.navigator.mediaCapabilities)return;const 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:Wo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:jo}})]);$t={[b.DASH_WEBM_AV1]:e,[b.DASH_WEBM]:t}};try{Mv()}catch(i){console.error(i)}const yi=Et.hls&&_e.mp4,Bv=()=>Object.keys(Qe).filter(i=>Qe[i]),Nv=(i,e=!1,t=!1)=>{const s=Et.mse||Et.mms&&t;return i.filter(r=>{switch(r){case b.DASH_SEP:return s&&_e.mp4&&fi;case b.DASH_WEBM:return s&&_e.webm&&Qe.vp9&&Qe.opus;case b.DASH_WEBM_AV1:return s&&_e.webm&&Qe.av1&&Qe.opus;case b.DASH_LIVE:return Et.mse&&_e.mp4&&fi;case b.DASH_LIVE_CMAF:return s&&_e.mp4&&fi&&_e.cmaf;case b.DASH_ONDEMAND:return s&&_e.mp4&&fi;case b.HLS:case b.HLS_ONDEMAND:return yi||e&&Et.mse&&_e.mp4&&fi;case b.HLS_LIVE:case b.HLS_LIVE_CMAF:return yi;case b.MPEG:return _e.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Et.webrtc&&Et.ws&&Qe.h264&&(_e.mp4||_e.webm);default:return U(r)}})},ht=i=>{const e=b.DASH_WEBM,t=b.DASH_WEBM_AV1;switch(i){case ft.VP9:return[e,t];case ft.AV1:return[t,e];case ft.NONE:return[];case ft.SMOOTH:return $t?$t[t].smooth?[t,e]:$t[e].smooth?[e,t]:[t,e]:[e,t];case ft.POWER_EFFICIENT:return $t?$t[t].powerEfficient?[t,e]:$t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:U(i)}return[e,t]},Fv=({webmCodec:i,androidPreferredFormat:e})=>{if(qo)switch(e){case $e.MPEG:return[b.MPEG,...ht(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case $e.HLS:return[b.HLS,b.HLS_ONDEMAND,...ht(i),b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG];case $e.DASH:return[...ht(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];case $e.DASH_ANY_MPEG:return[b.DASH_SEP,b.DASH_ONDEMAND,b.MPEG,...ht(i),b.HLS,b.HLS_ONDEMAND];case $e.DASH_ANY_WEBM:return[...ht(i),b.MPEG,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];case $e.DASH_SEP:return[b.DASH_SEP,b.MPEG,...ht(i),b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND];default:U(e)}return yi?[...ht(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]:[...ht(i),b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG]},Vv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[b.DASH_LIVE_CMAF,b.DASH_LIVE]:[b.DASH_LIVE,b.DASH_LIVE_CMAF],r=e?[b.HLS_LIVE_CMAF,b.HLS_LIVE]:[b.HLS_LIVE,b.HLS_LIVE_CMAF],a=[...s,...r],n=[...r,...s];let o;if(qo)switch(i){case $e.DASH:case $e.DASH_ANY_MPEG:case $e.DASH_ANY_WEBM:case $e.DASH_SEP:{o=a;break}case $e.HLS:case $e.MPEG:{o=n;break}default:U(i)}else yi?o=n:o=a;return t?[b.WEB_RTC_LIVE,...o]:[...o,b.WEB_RTC_LIVE]},xn=i=>i?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE_CMAF]:[b.DASH_WEBM,b.DASH_WEBM_AV1,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Uv=i=>new Br(e=>{const t=new ie,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:c})=>`${d}-${c}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe($(({type:d})=>d!==void 0)),n=new R;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Hv={chunkDuration:5e3,maxParallelRequests:5};class Gv{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new R,this.noAvailableProvidersError$=new R,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),autoVideoTrackLimits$:new y(void 0),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new R,warning$:new R,willSeekEvent$:new R,seekedEvent$:new R,loopedEvent$:new R,endedEvent$:new R,firstBytesEvent$:new R,firstFrameEvent$:new R,canplay$:new R,isLive$:new y(void 0),isLowLatency$:new y(!1),canChangePlaybackSpeed$:new y(!0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),inPiP$:new y(!1),inFullscreen$:new y(!1),element$:new y(void 0),elementVisible$:new y(!0),availableSources$:new y(void 0),is3DVideo$:new y(!1)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Nv([...Vv(this.params.tuning),...Fv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>L(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Dn(a);const n=[...xn(!0),...xn(!1)];this.chromecastFormatsIterator=new Dn(n.filter(o=>L(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 s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:_.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,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,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ye.SCREEN:return this.createScreenProvider(t);case ye.CHROMECAST:return this.createChromecastProvider(t);default:return U(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_WEBM_AV1:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t[b.HLS_ONDEMAND]||t[b.HLS]);return P(o),new bv({...n,source:o,sourceHls:u})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new yv({...n,source:o})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),yi||!this.params.tuning.useHlsJs?new kv({...n,source:o}):new Tv({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new wv({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new Pv({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new kp({...n,source:o,config:{...Hv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new _v({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Uf({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ye.CHROMECAST:ye.SCREEN}chooseFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return U(e)}}skipFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.next();case ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return U(e)}}handleNoFormatsError(e){switch(e){case ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return U(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return as(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,s=0;return e.add(N(this.providerOutput.error$,Uv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($(r=>({id:`ProviderHangup:${r}`,category:_.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(ce(({to:a})=>a===p.PLAYING),Te()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===_.NETWORK,o=r.category===_.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:ye.SCREEN)}})),e}}const Yv=5e3,_n="one_video_throughput",Rn="one_video_rtt",rt=window.navigator.connection,In=()=>{const i=rt==null?void 0:rt.downlink;if(L(i)&&i!==10)return i*1e3},Cn=()=>{const i=rt==null?void 0:rt.rtt;if(L(i)&&i!==3e3)return i},On=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class vi{constructor(e){var t,s;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=vi.load(_n)||(e.useBrowserEstimation?In():void 0)||Yv,a=(s=(t=vi.load(Rn))!==null&&t!==void 0?t:e.useBrowserEstimation?Cn():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(On(r,a,e.rttPenaltyRequestSize)),this.throughput=Or.getSmoothedValue(r,-1,e),this.rtt=Or.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=In();u&&this.throughput.next(u);const d=Cn();L(d)&&this.rtt.next(d)};rt&&"onchange"in rt&&this.subscription.add(I(rt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Is.set(_n,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Is.set(Rn,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ie({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>On(n,o,e.rttPenaltyRequestSize)),ce(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=oe();const r=new ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(I(e,"progress").pipe(Te()).subscribe(a=>{t=a.loaded,s=oe()}));break;case 1:case 0:r.add(I(e,"loadstart").subscribe(()=>{t=0,s=oe()}));break}r.add(I(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=oe(),u=n-t,d=o-s;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=oe(),n=0,o=oe();const u=c=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=async({done:c,value:l})=>{if(c)!t&&this.addRawSpeed(r,oe()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){if(oe()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=l.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=l.byteLength,a=oe()}o=oe()}else r+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&oe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,oe()-o,this.concurrentDownloads.size),n=0,o=oe());await(s==null?void 0:s.read().then(d,u))}};this.concurrentDownloads.add(e),s==null||s.read().then(d,u)}addRawSpeed(e,t,s=1,r=!1){if(vi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=Is.get(e);if(L(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Mn={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:Pe.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Pe.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:ft.VP9,androidPreferredFormat:$e.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}},qv=i=>{var e;return{...Td(i,Mn),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Mn.configName]}};var Bn=({seekState:i,position$:e})=>N(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ce(L)),e.pipe(ce(()=>i.getState().state===Y.None))),jv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const Wv=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ce(r=>r.length>0),Te()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class Xv{constructor(e={configName:[]}){if(this.subscription=new ie,this.logger=new Ed,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new y(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new ue(p.STOPPED),seekState:new ue({state:Y.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),internalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({}),cameraOrientation:new ue({x:0,y:0})},this.info={playbackState$:new y(p.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),canChangePlaybackSpeed$:new y(void 0),atLiveEdge$:new y(void 0),atLiveDurationEdge$:new y(void 0),liveTime$:new y(void 0),liveBufferTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),surface$:new y(Ze.NONE),chromecastState$:new y(ge.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0),availableSources$:new y(void 0),is3DVideo$:new y(!1),currentVideoSegmentLength$:new y(0),currentAudioSegmentLength$:new y(0)},this.events={inited$:new R,ready$:new R,started$:new R,playing$:new R,paused$:new R,stopped$:new R,willStart$:new R,willResume$:new R,willPause$:new R,willStop$:new R,willDestruct$:new R,watchCoverageRecord$:new R,watchCoverageLive$:new R,managedError$:new R,fatalError$:new R,ended$:new R,looped$:new R,seeked$:new R,willSeek$:new R,firstBytes$:new R,firstFrame$:new R,canplay$:new R,log$:new R},this.experimental={element$:new y(void 0),tuningConfigName$:new y([]),enableDebugTelemetry$:new y(!1),dumpTelemetry:dp},this.initLogs(),this.tuning=qv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wd({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(l=>JSON.stringify(l,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=jv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Gv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!_r()?I(document,"visibilitychange").pipe(Te()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.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()===ge.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()===ge.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(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(ce(s=>s.length>0),Te()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Wv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.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(),s=t.state===Y.None?void 0:t.position;return L(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(N(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ce(({from:e})=>e===p.STOPPED),Te()).subscribe(()=>{this.initedAt=oe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===Y.Requested?this.desiredState.seekState.setState({...n,state:Y.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.None}),this.events.seeked$.next())})).add(e.current$.pipe($(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(n=>n.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(n=>n.map(({quality:o})=>o).sort((o,u)=>Pt(o)?1:Pt(u)?-1:Zt(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe($(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(Ie({hasLiveOffsetByPaused:N(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(n=>n.to),he(),$(n=>n===p.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(Ie({atLiveEdge:Ie({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe($(({isLive:n,position:o,isLowLatency:u})=>{const d=this.getActiveLiveDelay(u);return n&&Math.abs(o)<d/1e3}),he(),gi(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe($(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ie({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe($(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),he(),gi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe($(n=>n.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(n=>n.volume),he()).subscribe(this.info.volume$)).add(Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(N(e.providerOutput.endedEvent$.pipe(es(!0)),e.providerOutput.seekedEvent$.pipe(es(!1))).pipe(he()).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($(n=>({id:n?`No${n}`:"NoProviders",category:_.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(Te(),$(n=>n!=null?n:oe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Te(),$(()=>oe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Te(),$(()=>oe()-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 y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ce(({to:n})=>n===p.PLAYING),Te()).subscribe(()=>s.next(!1)));let r=0;const a=N(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),he());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(N(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(N(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(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue();let l;c===ge.CONNECTED?l=Ze.SECOND_SCREEN:u?d?n?l=Ze.PIP:o?l=Ze.FULLSCREEN:l=Ze.INLINE:l=Ze.INVISIBLE:l=Ze.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ce(s=>s.length>0),Te()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=bs(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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(N(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),op(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>np(s)),this.providerContainer.current$.subscribe(({type:s})=>Vi("provider",s)),t.duration$.subscribe(s=>Vi("duration",s)),t.availableVideoTracks$.pipe(ce(s=>!!s.length),Te()).subscribe(s=>Vi("tracks",s)),this.events.fatalError$.subscribe(new We("fatalError")),this.events.managedError$.subscribe(new We("managedError")),t.position$.subscribe(new We("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new We("quality")),this.info.currentBuffer$.subscribe(new We("buffer")),t.isBuffering$.subscribe(new We("isBuffering"))].forEach(s=>this.subscription.add(s)),Vi("codecs",Bv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:_.DOM,message:String(r)})})};this.subscription.add(N(I(document,"visibilitychange"),I(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const Zv=`@vkontakte/videoplayer-core@${$d}`;export{ge as ChromecastState,yr as HttpConnectionType,ig as Observable,p as PlaybackState,Xv as Player,Zv as SDK_VERSION,sg as Subject,rg as Subscription,Ze as Surface,$d as VERSION,ag as ValueSubject,b as VideoFormat,ng 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 ps=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 cs(this.params.fov,this.params.orientation),this.cameraRotationManager=new ds(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(Nb,this.gl.VERTEX_SHADER),r=this.createShader(Fb,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,p=t+a;return[s,n,o,l,u,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Ht=class{constructor(e){this.subscription=new SA;this.videoState=new L("stopped");this.elementSize$=new Gb(void 0);this.textTracksManager=new Se;this.droppedFramesManager=new Za;this.videoTracks$=new Gb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new za;this.textTracks=[];this.syncPlayback=()=>{var n,o,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let u=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-u,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==null?void 0:r.to)==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(l=this.liveOffset)==null||l.pause(),this.video.pause()):(r==null?void 0: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==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return dA(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new ps(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ae(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(Q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ls({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=oe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:yu.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(Tu(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(hA(mA),vA()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ve(this.video,t.playbackRate,r.playbackRateState$,a)),s(gA(this.video),this.elementSize$),s(Te(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})=>{var c;if(u==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();qb(p,"Manifest not loaded or empty");let f=Array.from(p.audio).sort((S,g)=>g.bitrate-S.bitrate),h=Array.from(p.video).sort((S,g)=>g.bitrate-S.bitrate),b=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of f){let g=yb(S);g&&this.audioTracks.push({track:g,representation:S})}for(let S of h){let g=Sb(S);if(g){d.push({track:g,representation:S});let I=!this.params.tuning.isAudioDisabled&&Tb(f,h,S);I&&this.audioRepresentations.set(S.id,I)}}this.videoTracks$.next(d);for(let S of b){let g=Ib(S);g&&this.textTracks.push({track:g,representation:S})}this.params.output.availableVideoTracks$.next(d.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let v=this.selectVideoRepresentation();qb(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.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:yu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(hs(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$,fA(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(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let f=this.params.desiredState.autoVideoTrackSwitching.getState(),h=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let b=d.id;!this.params.output.elementVisible$.getValue()&&f&&(b=this.videoTracks$.getValue().map(S=>S.representation).sort((S,g)=>g.bitrate-S.bitrate).filter(S=>{let g=jb(S),I=jb(d);if(g&&I)return Hb(g,I)&&Hb(g,h)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",b).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.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(Ub(),Tu(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===u))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,d;if(u!=null&&u.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Tu(({to:u})=>u==="ready"),Ub());this.subscription.add(hs(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(hs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=hs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,bA(["init"])).pipe(pA(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,f,h,b,v,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=pt(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&&(h=(f=this.audioRepresentations.get(r.id))==null?void 0:f.bitrate)!=null?h:0,a&&(v=(b=this.audioRepresentations.get(a.id))==null?void 0:b.bitrate)!=null?v:0),u=dt(this.videoTracks$.getValue().map(({track:g})=>g),{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!=null?u:r:r!=null?r:u;return c&&((S=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ue(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.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:yu.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),se(this.video)}};var Oi=class extends Ht{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 Yb,interval as yA,map as TA}from"@vkontakte/videoplayer-shared";var Bi=class extends Ht{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(Yb({interval:yA(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(Yb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(TA(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var Qb=Oe(Ga(),1);import{assertNever as Vi,assertNonNullable as Wb,debounce as IA,ErrorCategory as fs,filter as EA,isNonNullable as xA,isNullable as PA,map as Iu,merge as wA,Observable as kA,observableFrom as AA,Subscription as RA,videoSizeToQuality as LA}from"@vkontakte/videoplayer-shared";var Ce={};var xr=(i,e)=>new kA(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),_i=class{constructor(e){this.subscription=new RA;this.videoState=new L("initializing");this.textTracksManager=new Se;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Vi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Vi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Vi(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:Vi(e)}break;default:Vi(t)}};this.video=ae(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(Q(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:fs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Qb.default)(import("hls.js").then(a=>{e||(Ce.Hls=a.default,Ce.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Wb(Ce.Hls,"hls.js not loaded"),this.hls=new Ce.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Wb(Ce.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:fs.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=oe(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(ne(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ve(this.video,e.playbackRate,a.playbackRateState$,r)),s(Te(this.video),t.elementVisible$),this.subscription.add(xr(this.hls,Ce.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:fs.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)==null?void 0:c.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(()=>{var u;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(xr(this.hls,Ce.Events.MANIFEST_PARSED).pipe(Iu(({levels:u})=>u.reduce((c,d)=>{var g,I;let p=d.name||d.height.toString(10),{width:f,height:h}=d,b=(I=lt((g=d.attrs.QUALITY)!=null?g:""))!=null?I:LA({width:f,height:h});if(!b)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:f,height:h},fps:v};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(xr(this.hls,Ce.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,f=d.attrs.URI||"",h=d.lang,b="internal";c.push({id:p,url:f,language:h,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(xr(this.hls,Ce.Events.LEVEL_LOADING).pipe(Iu(({url:u})=>Q(u))),t.hostname$),s(xr(this.hls,Ce.Events.FRAG_CHANGED),u=>{var p,f,h,b;let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3),t.currentAudioSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(nt(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=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===u))==null?void 0:c.track},o=xr(this.hls,Ce.Events.LEVEL_SWITCHED).pipe(Iu(({level:u})=>n(this.hls.levels[u])));o.pipe(EA(xA)).subscribe(t.currentVideoTrack$,r),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{var h;if(PA(u))return;let c=(h=this.trackLevels.get(u.id))==null?void 0:h.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,f=this.hls.levels[p];!f||c.bitrate>f.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=wA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,AA(["init"])).pipe(IA(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 ue(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fs.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 zb="X-Playback-Duration",Eu=async i=>{var a;let e=await Qe(i),t=await e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(zb)?parseInt(e.headers.get(zb),10):void 0};import{assertNever as BA,combine as VA,debounce as _A,ErrorCategory as bs,filter as NA,filterChanged as FA,isNonNullable as Jb,isNullable as gs,map as Xb,merge as qA,observableFrom as UA,Subscription as HA,ValueSubject as wu,VideoQuality as jA}from"@vkontakte/videoplayer-shared";var Pu=Oe(Da(),1);import{videoSizeToQuality as $A,getExponentialDelay as CA}from"@vkontakte/videoplayer-shared";var DA=i=>{let e=null;if(i.QUALITY&&(e=lt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=$A({width:t,height:r})}return e!=null?e:null},MA=(i,e)=>{var s,n;let t=i.split(`
92
+ `),r=[],a=[];for(let o=0;o<t.length;o++){let l=t[o],u=l.match(/^#EXT-X-STREAM-INF:(.+)/),c=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!c)){if(u){let d=(0,Pu.default)(u[1].split(",").map(g=>g.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,f=DA(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[g,I]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));g&&I&&(v={width:g,height:I})}let S=new URL(t[++o],e).toString();f&&r.push({id:p,quality:f,url:S,bandwidth:h,size:v,fps:b})}if(c){let d=(0,Pu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),f=d.LANGUAGE,h=d.NAME;p&&f&&a.push({type:"internal",id:f,label:h,language:f,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},OA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),xu=0,Kb=async(i,e=i,t)=>{let a=await(await Qe(i)).text();xu+=1;try{let{qualityManifests:s,textTracks:n}=MA(a,e);return{qualityManifests:s,textTracks:n}}catch(s){if(xu<=t.manifestRetryMaxCount)return await OA(CA(xu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kb(i,e,t)}return{qualityManifests:[],textTracks:[]}},ms=Kb;var Ni=class{constructor(e){this.subscription=new HA;this.videoState=new L("stopped");this.textTracksManager=new Se;this.manifests$=new wu([]);this.liveOffset=new Ye;this.manifestStartTime$=new wu(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==null?void 0: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==null?void 0: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==null?void 0:a.to)==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return BA(t)}};var t;this.params=e,this.video=ae(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jA.INVARIANT,url:this.params.source.url},ms(J(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:bs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:bs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Q(this.params.source.url)),this.maxSeekBackTime$=new wu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var l,u,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(l=a==null?void 0:a.to)==null?void 0:l.id)!=null?c:(u=t.getState())==null?void 0:u.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:bs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=oe(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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(FA(),Xb(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&&Jb(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Q(p.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(()=>{var l,u,c;let o=(c=(u=(l=this.video)==null?void 0:l.getStartDate)==null?void 0:u.call(l))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(VA({startTime:this.manifestStartTime$.pipe(NA(Jb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(Xb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=qA(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,UA(["init"])).pipe(_A(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){var o,l;let e=this.selectManifest();if(gs(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:u,min:c}=(l=(o=t==null?void 0:t.to)!=null?o:r)!=null?l:{};for(let[d,p]of[[u,"mq"],[c,"lq"]]){let f=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=J(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Eu(n).then(u=>{var c;if(!gs(u))this.maxSeekBackTime$.next(u);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(gs(d)||!isFinite(d))try{Qe(n).then(p=>p.text()).then(p=>{var h;let f=(h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:h[1];if(f){let b=new URL(f,n).toString();Eu(b).then(v=>{gs(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){ue(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:bs.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 GA,debounce as YA,ErrorCategory as ku,fromEvent as Au,isNonNullable as WA,isNullable as QA,map as zA,merge as Zb,observableFrom as eg,Subscription as KA,ValueSubject as JA,VideoQuality as XA,isIOS as ZA}from"@vkontakte/videoplayer-shared";var Fi=class{constructor(e){this.subscription=new KA;this.videoState=new L("stopped");this.textTracksManager=new Se;this.manifests$=new JA([]);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==null?void 0: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==null?void 0:a.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return GA(t)}};this.params=e,this.video=ae(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:XA.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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ms(J(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:ku.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var l,u,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(l=a==null?void 0:a.to)==null?void 0:l.id)!=null?c:(u=t.getState())==null?void 0:u.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:ku.WTF,message:"HlsProvider internal logic error",thrown:o})},a=oe(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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&WA(u.to)){let p=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let f=this.manifests$.getValue().find(h=>h.id===p);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Q(f.url));let h=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(h!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(h),v.playbackRate=h)}}}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(zA(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!ZA()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Zb(Au(o,"addtrack"),Au(o,"removetrack"),Au(o,"change"),eg(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=Zb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eg(["init"])).pipe(YA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){var s,n;let e=this.selectManifest();if(QA(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}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ue(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:ku.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as eR,assertNonNullable as tg,debounce as tR,ErrorCategory as rg,isHigher as rR,isHigherOrEqual as iR,isInvariantQuality as ig,isLowerOrEqual as aR,isNonNullable as sR,merge as nR,observableFrom as oR,Subscription as uR}from"@vkontakte/videoplayer-shared";var qi=class{constructor(e){this.subscription=new uR;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Se;this.syncPlayback=()=>{var l,u,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((l=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:l.max)!==((c=(u=this.trackUrls[n.to.id])==null?void 0:u.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?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==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return eR(e)}};this.params=e,this.video=ae(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:rg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=oe(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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(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(()=>{var l,u;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&sR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(u=this.params.output.element$.getValue())==null?void 0:u.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=nR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,oR(["init"])).pipe(tR(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),se(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;tg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ci(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Q(t))}playIfAllowed(){ue(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:rg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let l=(s=Object.values(this.trackUrls).find(d=>!ig(d.track.quality)&&aR(d.track.quality,e)))==null?void 0:s.track,u=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[u!=null?u:"0"])==null?void 0:o.track;if(l&&c&&iR(c.quality,l.quality)&&(t=l),!t){let d=Object.values(this.trackUrls).filter(f=>!ig(f.track.quality)&&rR(f.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let l=Object.values(this.trackUrls).map(u=>u.track);t=dt(l,{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 sg,debounce as pR,merge as ng,observableFrom as hR,Subscription as fR,map as og,ValueSubject as mR,ErrorCategory as Lu,VideoQuality as bR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as lR}from"@vkontakte/videoplayer-shared";var ag=["stun:videostun.mycdn.me:80"],cR=1e3,dR=3,Ru=()=>null,vs=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=Ru;this.externalStopCallback=Ru;this.externalErrorCallback=Ru;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:ag}]};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:lR.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(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),cR)}normalizeOptions(e={}){let t={stunServerList:ag,maxRetryNumber:dR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ui=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new mR(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==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return sg(e)}};this.subscription=new fR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container),this.liveStreamClient=new vs(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),se(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})};ng(this.videoState.stateChangeStarted$.pipe(og(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(og(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=oe(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(Te(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ne(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 sg(n.to)}},r)).add(ng(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,hR(["init"])).pipe(pR(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(Q(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:bR.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(){ue(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 Hi=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 Gi,assertNonNullable as bt,ErrorCategory as ws,filter as RR,isNonNullable as kg,isNullable as LR,map as $R,merge as CR,once as DR,Subject as De,Subscription as Ag,ValueSubject as O}from"@vkontakte/videoplayer-shared";import{assertNever as Ps,CurrentClientDevice as SR,getCurrentBrowser as yR}from"@vkontakte/videoplayer-shared";var vg=yR().device===SR.Android,Ee=document.createElement("video"),TR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',IR='video/mp4; codecs="hev1.1.6.L93.B0"',Sg='video/webm; codecs="vp09.00.10.08"',yg='video/webm; codecs="av01.0.00M.08"',ER='audio/mp4; codecs="mp4a.40.2"',xR='audio/webm; codecs="opus"',ug,lg,jt={mms:os(),mse:$b(),hls:!!((ug=Ee.canPlayType)!=null&&ug.call(Ee,"application/x-mpegurl")||(lg=Ee.canPlayType)!=null&&lg.call(Ee,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},cg,dg,Ie={mp4:!!((cg=Ee.canPlayType)!=null&&cg.call(Ee,"video/mp4")),webm:!!((dg=Ee.canPlayType)!=null&&dg.call(Ee,"video/webm")),cmaf:!0},Ss,pg,ys,hg,Ts,fg,Is,mg,Es,bg,xs,gg,Fe={h264:!!((pg=(Ss=Xe())==null?void 0:Ss.isTypeSupported)!=null&&pg.call(Ss,TR)),h265:!!((hg=(ys=Xe())==null?void 0:ys.isTypeSupported)!=null&&hg.call(ys,IR)),vp9:!!((fg=(Ts=Xe())==null?void 0:Ts.isTypeSupported)!=null&&fg.call(Ts,Sg)),av1:!!((mg=(Is=Xe())==null?void 0:Is.isTypeSupported)!=null&&mg.call(Is,yg)),aac:!!((bg=(Es=Xe())==null?void 0:Es.isTypeSupported)!=null&&bg.call(Es,ER)),opus:!!((gg=(xs=Xe())==null?void 0:xs.isTypeSupported)!=null&&gg.call(xs,xR))},ji=(Fe.h264||Fe.h265)&&Fe.aac,Gt,PR=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:yg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Sg}})]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{PR()}catch(i){console.error(i)}var Pr=jt.hls&&Ie.mp4,Tg=()=>Object.keys(Fe).filter(i=>Fe[i]),Ig=(i,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Ie.mp4&&ji;case"DASH_WEBM":return r&&Ie.webm&&Fe.vp9&&Fe.opus;case"DASH_WEBM_AV1":return r&&Ie.webm&&Fe.av1&&Fe.opus;case"DASH_LIVE":return jt.mse&&Ie.mp4&&ji;case"DASH_LIVE_CMAF":return r&&Ie.mp4&&ji&&Ie.cmaf;case"DASH_ONDEMAND":return r&&Ie.mp4&&ji;case"HLS":case"HLS_ONDEMAND":return Pr||e&&jt.mse&&Ie.mp4&&ji;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pr;case"MPEG":return Ie.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Fe.h264&&(Ie.mp4||Ie.webm);default:return Ps(a)}})},mt=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ps(i)}return[e,t]},Eg=({webmCodec:i,androidPreferredFormat:e})=>{if(vg)switch(e){case"mpeg":return["MPEG",...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...mt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...mt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:Ps(e)}return Pr?[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},xg=({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(vg)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:Ps(i)}else Pr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},$u=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 wR,map as Pg,Subscription as kR,Subject as AR}from"@vkontakte/videoplayer-shared";var wg=i=>new wR(e=>{let t=new kR,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Pg(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Pg(({type:u})=>u!==void 0)),n=new AR,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 MR={chunkDuration:5e3,maxParallelRequests:5},Yi=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new De;this.noAvailableProvidersError$=new De;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),currentVideoTrack$:new O(void 0),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),availableVideoTracks$:new O([]),availableAudioTracks$:new O([]),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new De,warning$:new De,willSeekEvent$:new De,seekedEvent$:new De,loopedEvent$:new De,endedEvent$:new De,firstBytesEvent$:new De,firstFrameEvent$:new De,canplay$:new De,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1)};this.subscription=new Ag;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ig([...xg(this.params.tuning),...Eg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>kg(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 Hi(s);let n=[...$u(!0),...$u(!1)];this.chromecastFormatsIterator=new Hi(n.filter(o=>kg(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(LR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ws.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 Gi(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 bt(o),new Oi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Bi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return bt(o),Pr||!this.params.tuning.useHlsJs?new Fi({...n,source:o}):new _i({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Ni({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return bt(o),new qi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new km({...n,source:o,config:{...MR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new Ui({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 Gi(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 bt(o),new zr({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 Gi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Gi(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 Gi(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,Rg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Ag,t=!1,r=0;return e.add(CR(this.providerOutput.error$,wg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($R(a=>({id:`ProviderHangup:${a}`,category:ws.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(RR(({to:s})=>s==="playing"),DR()).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===ws.NETWORK,o=a.category===ws.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!=null?s:"SCREEN")}})),e}};import{fromEvent as ks,once as OR,combine as BR,Subscription as Lg,ValueSubject as Cu,map as VR,filter as _R,isNonNullable as As,now as fe,safeStorage as Du}from"@vkontakte/videoplayer-shared";var NR=5e3,$g="one_video_throughput",Cg="one_video_rtt",Ze=window.navigator.connection,Dg=()=>{let i=Ze==null?void 0:Ze.downlink;if(As(i)&&i!==10)return i*1e3},Mg=()=>{let i=Ze==null?void 0:Ze.rtt;if(As(i)&&i!==3e3)return i},Og=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Mu=class i{constructor(e){this.subscription=new Lg;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load($g)||(e.useBrowserEstimation?Dg():void 0)||NR,r=(s=(a=i.load(Cg))!=null?a:e.useBrowserEstimation?Mg():void 0)!=null?s:0;if(this.throughput$=new Cu(t),this.rtt$=new Cu(r),this.rttAdjustedThroughput$=new Cu(Og(t,r,e.rttPenaltyRequestSize)),this.throughput=Ft.getSmoothedValue(t,-1,e),this.rtt=Ft.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let l=Dg();l&&this.throughput.next(l);let u=Mg();As(u)&&this.rtt.next(u)};Ze&&"onchange"in Ze&&this.subscription.add(ks(Ze,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Du.set($g,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Du.set(Cg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(BR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(VR(({throughput:n,rtt:o})=>Og(n,o,e.rttPenaltyRequestSize)),_R(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=fe(),a=new Lg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(ks(e,"progress").pipe(OR()).subscribe(s=>{t=s.loaded,r=fe()}));break;case 1:case 0:a.add(ks(e,"loadstart").subscribe(()=>{t=0,r=fe()}));break}a.add(ks(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=fe(),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=fe(),n=0,o=fe(),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,fe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(fe()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=fe()}o=fe()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,fe()-o,this.concurrentDownloads.size),n=0,o=fe());await(r==null?void 0:r.read().then(u,l))}};this.concurrentDownloads.add(e),r==null||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){var r;let t=Du.get(e);if(As(t))return(r=parseInt(t,10))!=null?r:void 0}},Bg=Mu;import{fillWithDefault as FR,VideoQuality as Vg}from"@vkontakte/videoplayer-shared";var _g={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:Vg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Vg.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}},Ng=i=>{var e;return{...FR(i,_g),configName:[...(e=i.configName)!=null?e:[],..._g.configName]}};import{assertNonNullable as Rs,combine as Ls,ErrorCategory as $s,filter as Wi,filterChanged as xe,fromEvent as Bu,isNonNullable as WR,isNullable as QR,Logger as zR,map as D,mapTo as Hg,merge as gt,now as Cs,once as et,Subject as F,Subscription as jg,tap as Gg,ValueSubject as P,isHigher as KR,isInvariantQuality as Yg}from"@vkontakte/videoplayer-shared";import{merge as qR,map as UR,filter as Fg,isNonNullable as HR}from"@vkontakte/videoplayer-shared";var Ou=({seekState:i,position$:e})=>qR(i.stateChangeEnded$.pipe(UR(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),Fg(HR)),e.pipe(Fg(()=>i.getState().state==="none")));import{assertNonNullable as jR}from"@vkontakte/videoplayer-shared";var qg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return jR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as GR,once as YR}from"@vkontakte/videoplayer-shared";var Ug=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(GR(a=>a.length>0),YR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Ds=class{constructor(e={configName:[]}){this.subscription=new jg;this.logger=new zR;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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:fm};if(this.initLogs(),this.tuning=Ng(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new aa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bg(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,(p,f)=>{let h=typeof f;return["number","string","boolean"].includes(h)?f:f===null?null:`<${h}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:$s.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=qg(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Yi({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ai()?Bu(document,"visibilitychange").pipe(et()).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){Rs(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(Wi(r=>r.length>0),et()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Rs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Ug(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(QR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return WR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Wi(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=Cs(),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:$s.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(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),xe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,l)=>Yg(o)?1:Yg(l)?-1:KR(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==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(xe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(xe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(xe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(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(Ls({hasLiveOffsetByPaused:gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),xe(),D(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(Ls({atLiveEdge:Ls({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ou({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),xe(),Gg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ls({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),xe(),Gg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),xe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),xe()).subscribe(this.info.volume$)).add(Ou({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(gt(e.providerOutput.endedEvent$.pipe(Hg(!0)),e.providerOutput.seekedEvent$.pipe(Hg(!1))).pipe(xe()).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(D(n=>({id:n?`No${n}`:"NoProviders",category:$s.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(et(),D(n=>n!=null?n:Cs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),D(()=>Cs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),D(()=>Cs()-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(Wi(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=gt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),xe());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(gt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var l,u;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=n==null?void 0:n.size)==null?void 0:l.width,height:(u=n==null?void 0:n.size)==null?void 0:u.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(gt(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(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new jg;this.subscription.add(t),this.subscription.add(e.current$.pipe(xe((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Wi(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=dt(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(gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Rs(this.providerContainer),Rs(e),hm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>pm(r)),this.providerContainer.current$.subscribe(({type:r})=>Zr("provider",r)),e.duration$.subscribe(r=>Zr("duration",r)),e.availableVideoTracks$.pipe(Wi(r=>!!r.length),et()).subscribe(r=>Zr("tracks",r)),this.events.fatalError$.subscribe(new Z("fatalError")),this.events.managedError$.subscribe(new Z("managedError")),e.position$.subscribe(new Z("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new Z("quality")),this.info.currentBuffer$.subscribe(new Z("buffer")),e.isBuffering$.subscribe(new Z("isBuffering"))].forEach(r=>this.subscription.add(r)),Zr("codecs",Tg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||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:$s.DOM,message:String(a)})})};this.subscription.add(gt(Bu(document,"visibilitychange"),Bu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as JH,Observable as XH,Subject as ZH,ValueSubject as ej,VideoQuality as tj}from"@vkontakte/videoplayer-shared";var rj=`@vkontakte/videoplayer-core@${rl}`;export{ra as ChromecastState,js as HttpConnectionType,XH as Observable,ce as PlaybackState,Ds as Player,rj as SDK_VERSION,ZH as Subject,JH as Subscription,Gs as Surface,rl as VERSION,ej as ValueSubject,Et as VideoFormat,tj as VideoQuality};