@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.cjs.js CHANGED
@@ -1,46 +1,92 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.103
3
- * Tue, 18 Jun 2024 13:19:48 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-103/doc/
2
+ * @vkontakte/videoplayer-core v2.0.104
3
+ * Mon, 24 Jun 2024 13:01:09 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
5
5
  */
6
- "use strict";var xo=Object.create;var Ra=Object.defineProperty;var _o=Object.getOwnPropertyDescriptor;var Ro=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,No=Object.prototype.hasOwnProperty;var Oo=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ro(e))!No.call(i,a)&&a!==t&&Ra(i,a,{get:()=>e[a],enumerable:!(s=_o(e,a))||s.enumerable});return i};var Mo=(i,e,t)=>(t=i!=null?xo(Io(i)):{},Oo(e||!i||!i.__esModule?Ra(t,"default",{value:i,enumerable:!0}):t,i));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js");const tn="2.0.103";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ae;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ae||(ae={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var I;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(I||(I={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip",i.INVISIBLE="invisible"})(exports.Surface||(exports.Surface={}));var Bo=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 Vo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Bo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,a,n;(n=(a=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([s.getCastState()])).pipe(r.filterChanged(),r.map(Fo),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const c=s.getCurrentSession();r.assertNonNullable(c);const u=c.getCastDevice(),h=(n=c.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.isNullable(h)||h===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,s,a;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Fo=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return r.assertNever(i)}};var ts=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ta(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Oe=function(i){try{return!!i()}catch(e){return!0}},Uo=Oe,_i=!Uo(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),sn=_i,an=Function.prototype,Fs=an.call,jo=sn&&an.bind.bind(Fs,Fs),Me=sn?jo:function(i){return function(){return Fs.apply(i,arguments)}},rn=Me,Ho=rn({}.toString),Go=rn("".slice),Ri=function(i){return Go(Ho(i),8,-1)},Yo=Me,qo=Oe,zo=Ri,is=Object,Wo=Yo("".split),Qo=qo(function(){return!is("z").propertyIsEnumerable(0)})?function(i){return zo(i)=="String"?Wo(i,""):is(i)}:is,Ii=function(i){return i==null},Ko=Ii,Jo=TypeError,ia=function(i){if(Ko(i))throw Jo("Can't call method on "+i);return i},Xo=Qo,Zo=ia,zt=function(i){return Xo(Zo(i))},xt={},ai=function(i){return i&&i.Math==Math&&i},ye=ai(typeof globalThis=="object"&&globalThis)||ai(typeof window=="object"&&window)||ai(typeof self=="object"&&self)||ai(typeof ts=="object"&&ts)||function(){return this}()||ts||Function("return this")(),Us=typeof document=="object"&&document.all,el=typeof Us=="undefined"&&Us!==void 0,nn={all:Us,IS_HTMLDDA:el},on=nn,tl=on.all,me=on.IS_HTMLDDA?function(i){return typeof i=="function"||i===tl}:function(i){return typeof i=="function"},il=ye,sl=me,Ia=il.WeakMap,al=sl(Ia)&&/native code/.test(String(Ia)),Na=me,ln=nn,rl=ln.all,at=ln.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Na(i)||i===rl}:function(i){return typeof i=="object"?i!==null:Na(i)},nl=Oe,rt=!nl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),_t={},ol=ye,Oa=at,js=ol.document,ll=Oa(js)&&Oa(js.createElement),un=function(i){return ll?js.createElement(i):{}},ul=rt,dl=Oe,cl=un,dn=!ul&&!dl(function(){return Object.defineProperty(cl("div"),"a",{get:function(){return 7}}).a!=7}),hl=rt,fl=Oe,cn=hl&&fl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),pl=at,ml=String,vl=TypeError,nt=function(i){if(pl(i))return i;throw vl(ml(i)+" is not an object")},Sl=_i,ri=Function.prototype.call,Be=Sl?ri.bind(ri):function(){return ri.apply(ri,arguments)},sa={},ss=sa,as=ye,bl=me,Ma=function(i){return bl(i)?i:void 0},aa=function(i,e){return arguments.length<2?Ma(ss[i])||Ma(as[i]):ss[i]&&ss[i][e]||as[i]&&as[i][e]},gl=Me,ra=gl({}.isPrototypeOf),yl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",hn=ye,rs=yl,Ba=hn.process,Va=hn.Deno,Fa=Ba&&Ba.versions||Va&&Va.version,Ua=Fa&&Fa.v8,be,ki;Ua&&(be=Ua.split("."),ki=be[0]>0&&be[0]<4?1:+(be[0]+be[1]));!ki&&rs&&(be=rs.match(/Edge\/(\d+)/),(!be||be[1]>=74)&&(be=rs.match(/Chrome\/(\d+)/),be&&(ki=+be[1])));var Tl=ki,ja=Tl,El=Oe,$l=ye,kl=$l.String,fn=!!Object.getOwnPropertySymbols&&!El(function(){var i=Symbol();return!kl(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&ja&&ja<41}),Al=fn,pn=Al&&!Symbol.sham&&typeof Symbol.iterator=="symbol",wl=aa,Pl=me,Cl=ra,Ll=pn,Dl=Object,mn=Ll?function(i){return typeof i=="symbol"}:function(i){var e=wl("Symbol");return Pl(e)&&Cl(e.prototype,Dl(i))},xl=String,na=function(i){try{return xl(i)}catch(e){return"Object"}},_l=me,Rl=na,Il=TypeError,oa=function(i){if(_l(i))return i;throw Il(Rl(i)+" is not a function")},Nl=oa,Ol=Ii,Ni=function(i,e){var t=i[e];return Ol(t)?void 0:Nl(t)},ns=Be,os=me,ls=at,Ml=TypeError,Bl=function(i,e){var t,s;if(e==="string"&&os(t=i.toString)&&!ls(s=ns(t,i))||os(t=i.valueOf)&&!ls(s=ns(t,i))||e!=="string"&&os(t=i.toString)&&!ls(s=ns(t,i)))return s;throw Ml("Can't convert object to primitive value")},vn={exports:{}},Ha=ye,Vl=Object.defineProperty,Fl=function(i,e){try{Vl(Ha,i,{value:e,configurable:!0,writable:!0})}catch(t){Ha[i]=e}return e},Ul=ye,jl=Fl,Ga="__core-js_shared__",Hl=Ul[Ga]||jl(Ga,{}),Sn=Hl,Ya=Sn;(vn.exports=function(i,e){return Ya[i]||(Ya[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 bn=vn.exports,Gl=ia,Yl=Object,Oi=function(i){return Yl(Gl(i))},ql=Me,zl=Oi,Wl=ql({}.hasOwnProperty),Ve=Object.hasOwn||function(e,t){return Wl(zl(e),t)},Ql=Me,Kl=0,Jl=Math.random(),Xl=Ql(1 .toString),gn=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Xl(++Kl+Jl,36)},Zl=ye,eu=bn,qa=Ve,tu=gn,iu=fn,su=pn,wt=Zl.Symbol,us=eu("wks"),au=su?wt.for||wt:wt&&wt.withoutSetter||tu,Te=function(i){return qa(us,i)||(us[i]=iu&&qa(wt,i)?wt[i]:au("Symbol."+i)),us[i]},ru=Be,za=at,Wa=mn,nu=Ni,ou=Bl,lu=Te,uu=TypeError,du=lu("toPrimitive"),cu=function(i,e){if(!za(i)||Wa(i))return i;var t=nu(i,du),s;if(t){if(e===void 0&&(e="default"),s=ru(t,i,e),!za(s)||Wa(s))return s;throw uu("Can't convert object to primitive value")}return e===void 0&&(e="number"),ou(i,e)},hu=cu,fu=mn,la=function(i){var e=hu(i,"string");return fu(e)?e:e+""},pu=rt,mu=dn,vu=cn,ni=nt,Qa=la,Su=TypeError,ds=Object.defineProperty,bu=Object.getOwnPropertyDescriptor,cs="enumerable",hs="configurable",fs="writable";_t.f=pu?vu?function(e,t,s){if(ni(e),t=Qa(t),ni(s),typeof e=="function"&&t==="prototype"&&"value"in s&&fs in s&&!s[fs]){var a=bu(e,t);a&&a[fs]&&(e[t]=s.value,s={configurable:hs in s?s[hs]:a[hs],enumerable:cs in s?s[cs]:a[cs],writable:!1})}return ds(e,t,s)}:ds:function(e,t,s){if(ni(e),t=Qa(t),ni(s),mu)try{return ds(e,t,s)}catch(a){}if("get"in s||"set"in s)throw Su("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Mi=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},gu=rt,yu=_t,Tu=Mi,Wt=gu?function(i,e,t){return yu.f(i,e,Tu(1,t))}:function(i,e,t){return i[e]=t,i},Eu=bn,$u=gn,Ka=Eu("keys"),ua=function(i){return Ka[i]||(Ka[i]=$u(i))},da={},ku=al,yn=ye,Au=at,wu=Wt,ps=Ve,ms=Sn,Pu=ua,Cu=da,Ja="Object already initialized",Hs=yn.TypeError,Lu=yn.WeakMap,Ai,Gt,wi,Du=function(i){return wi(i)?Gt(i):Ai(i,{})},xu=function(i){return function(e){var t;if(!Au(e)||(t=Gt(e)).type!==i)throw Hs("Incompatible receiver, "+i+" required");return t}};if(ku||ms.state){var ke=ms.state||(ms.state=new Lu);ke.get=ke.get,ke.has=ke.has,ke.set=ke.set,Ai=function(i,e){if(ke.has(i))throw Hs(Ja);return e.facade=i,ke.set(i,e),e},Gt=function(i){return ke.get(i)||{}},wi=function(i){return ke.has(i)}}else{var bt=Pu("state");Cu[bt]=!0,Ai=function(i,e){if(ps(i,bt))throw Hs(Ja);return e.facade=i,wu(i,bt,e),e},Gt=function(i){return ps(i,bt)?i[bt]:{}},wi=function(i){return ps(i,bt)}}var _u={set:Ai,get:Gt,has:wi,enforce:Du,getterFor:xu},Ru=_i,Tn=Function.prototype,Xa=Tn.apply,Za=Tn.call,Iu=typeof Reflect=="object"&&Reflect.apply||(Ru?Za.bind(Xa):function(){return Za.apply(Xa,arguments)}),Nu=Ri,Ou=Me,En=function(i){if(Nu(i)==="Function")return Ou(i)},$n={},kn={},An={}.propertyIsEnumerable,wn=Object.getOwnPropertyDescriptor,Mu=wn&&!An.call({1:2},1);kn.f=Mu?function(e){var t=wn(this,e);return!!t&&t.enumerable}:An;var Bu=rt,Vu=Be,Fu=kn,Uu=Mi,ju=zt,Hu=la,Gu=Ve,Yu=dn,er=Object.getOwnPropertyDescriptor;$n.f=Bu?er:function(e,t){if(e=ju(e),t=Hu(t),Yu)try{return er(e,t)}catch(s){}if(Gu(e,t))return Uu(!Vu(Fu.f,e,t),e[t])};var qu=Oe,zu=me,Wu=/#|\.prototype\./,Qt=function(i,e){var t=Ku[Qu(i)];return t==Xu?!0:t==Ju?!1:zu(e)?qu(e):!!e},Qu=Qt.normalize=function(i){return String(i).replace(Wu,".").toLowerCase()},Ku=Qt.data={},Ju=Qt.NATIVE="N",Xu=Qt.POLYFILL="P",Zu=Qt,tr=En,ed=oa,td=_i,id=tr(tr.bind),Pn=function(i,e){return ed(i),e===void 0?i:td?id(i,e):function(){return i.apply(e,arguments)}},oi=ye,sd=Iu,ad=En,rd=me,nd=$n.f,od=Zu,gt=sa,ld=Pn,yt=Wt,ir=Ve,ud=function(i){var e=function(t,s,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,s)}return new i(t,s,a)}return sd(i,this,arguments)};return e.prototype=i.prototype,e},Bi=function(i,e){var t=i.target,s=i.global,a=i.stat,n=i.proto,o=s?oi:a?oi[t]:(oi[t]||{}).prototype,l=s?gt:gt[t]||yt(gt,t,{})[t],c=l.prototype,u,h,d,f,p,v,m,S,b;for(f in e)u=od(s?f:t+(a?".":"#")+f,i.forced),h=!u&&o&&ir(o,f),v=l[f],h&&(i.dontCallGetSet?(b=nd(o,f),m=b&&b.value):m=o[f]),p=h&&m?m:e[f],!(h&&typeof v==typeof p)&&(i.bind&&h?S=ld(p,oi):i.wrap&&h?S=ud(p):n&&rd(p)?S=ad(p):S=p,(i.sham||p&&p.sham||v&&v.sham)&&yt(S,"sham",!0),yt(l,f,S),n&&(d=t+"Prototype",ir(gt,d)||yt(gt,d,{}),yt(gt[d],f,p),i.real&&c&&(u||!c[f])&&yt(c,f,p)))},Gs=rt,dd=Ve,Cn=Function.prototype,cd=Gs&&Object.getOwnPropertyDescriptor,ca=dd(Cn,"name"),hd=ca&&function(){}.name==="something",fd=ca&&(!Gs||Gs&&cd(Cn,"name").configurable),pd={EXISTS:ca,PROPER:hd,CONFIGURABLE:fd},Ln={},md=Math.ceil,vd=Math.floor,Sd=Math.trunc||function(e){var t=+e;return(t>0?vd:md)(t)},bd=Sd,ha=function(i){var e=+i;return e!==e||e===0?0:bd(e)},gd=ha,yd=Math.max,Td=Math.min,Ed=function(i,e){var t=gd(i);return t<0?yd(t+e,0):Td(t,e)},$d=ha,kd=Math.min,Ad=function(i){return i>0?kd($d(i),9007199254740991):0},wd=Ad,fa=function(i){return wd(i.length)},Pd=zt,Cd=Ed,Ld=fa,sr=function(i){return function(e,t,s){var a=Pd(e),n=Ld(a),o=Cd(s,n),l;if(i&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in a)&&a[o]===t)return i||o||0;return!i&&-1}},Dd={includes:sr(!0),indexOf:sr(!1)},xd=Me,vs=Ve,_d=zt,Rd=Dd.indexOf,Id=da,ar=xd([].push),Nd=function(i,e){var t=_d(i),s=0,a=[],n;for(n in t)!vs(Id,n)&&vs(t,n)&&ar(a,n);for(;e.length>s;)vs(t,n=e[s++])&&(~Rd(a,n)||ar(a,n));return a},Dn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Od=Nd,Md=Dn,Bd=Object.keys||function(e){return Od(e,Md)},Vd=rt,Fd=cn,Ud=_t,jd=nt,Hd=zt,Gd=Bd;Ln.f=Vd&&!Fd?Object.defineProperties:function(e,t){jd(e);for(var s=Hd(t),a=Gd(t),n=a.length,o=0,l;n>o;)Ud.f(e,l=a[o++],s[l]);return e};var Yd=aa,qd=Yd("document","documentElement"),zd=nt,Wd=Ln,rr=Dn,Qd=da,Kd=qd,Jd=un,Xd=ua,nr=">",or="<",Ys="prototype",qs="script",xn=Xd("IE_PROTO"),Ss=function(){},_n=function(i){return or+qs+nr+i+or+"/"+qs+nr},lr=function(i){i.write(_n("")),i.close();var e=i.parentWindow.Object;return i=null,e},Zd=function(){var i=Jd("iframe"),e="java"+qs+":",t;return i.style.display="none",Kd.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(_n("document.F=Object")),t.close(),t.F},li,yi=function(){try{li=new ActiveXObject("htmlfile")}catch(e){}yi=typeof document!="undefined"?document.domain&&li?lr(li):Zd():lr(li);for(var i=rr.length;i--;)delete yi[Ys][rr[i]];return yi()};Qd[xn]=!0;var Rn=Object.create||function(e,t){var s;return e!==null?(Ss[Ys]=zd(e),s=new Ss,Ss[Ys]=null,s[xn]=e):s=yi(),t===void 0?s:Wd.f(s,t)},ec=Oe,tc=!ec(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),ic=Ve,sc=me,ac=Oi,rc=ua,nc=tc,ur=rc("IE_PROTO"),zs=Object,oc=zs.prototype,In=nc?zs.getPrototypeOf:function(i){var e=ac(i);if(ic(e,ur))return e[ur];var t=e.constructor;return sc(t)&&e instanceof t?t.prototype:e instanceof zs?oc:null},lc=Wt,Nn=function(i,e,t,s){return s&&s.enumerable?i[e]=t:lc(i,e,t),i},uc=Oe,dc=me,cc=at,hc=Rn,dr=In,fc=Nn,pc=Te,Ws=pc("iterator"),On=!1,Ie,bs,gs;[].keys&&(gs=[].keys(),"next"in gs?(bs=dr(dr(gs)),bs!==Object.prototype&&(Ie=bs)):On=!0);var mc=!cc(Ie)||uc(function(){var i={};return Ie[Ws].call(i)!==i});mc?Ie={}:Ie=hc(Ie);dc(Ie[Ws])||fc(Ie,Ws,function(){return this});var Mn={IteratorPrototype:Ie,BUGGY_SAFARI_ITERATORS:On},vc=Te,Sc=vc("toStringTag"),Bn={};Bn[Sc]="z";var pa=String(Bn)==="[object z]",bc=pa,gc=me,Ti=Ri,yc=Te,Tc=yc("toStringTag"),Ec=Object,$c=Ti(function(){return arguments}())=="Arguments",kc=function(i,e){try{return i[e]}catch(t){}},Vi=bc?Ti:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=kc(e=Ec(i),Tc))=="string"?t:$c?Ti(e):(s=Ti(e))=="Object"&&gc(e.callee)?"Arguments":s},Ac=pa,wc=Vi,Pc=Ac?{}.toString:function(){return"[object "+wc(this)+"]"},Cc=pa,Lc=_t.f,Dc=Wt,xc=Ve,_c=Pc,Rc=Te,cr=Rc("toStringTag"),Vn=function(i,e,t,s){if(i){var a=t?i:i.prototype;xc(a,cr)||Lc(a,cr,{configurable:!0,value:e}),s&&!Cc&&Dc(a,"toString",_c)}},Ic=Mn.IteratorPrototype,Nc=Rn,Oc=Mi,Mc=Vn,Bc=xt,Vc=function(){return this},Fc=function(i,e,t,s){var a=e+" Iterator";return i.prototype=Nc(Ic,{next:Oc(+!s,t)}),Mc(i,a,!1,!0),Bc[a]=Vc,i},Uc=Bi,jc=Be,Fn=pd,Hc=Fc,Gc=In,Yc=Vn,hr=Nn,qc=Te,fr=xt,Un=Mn,zc=Fn.PROPER;Fn.CONFIGURABLE;Un.IteratorPrototype;var ui=Un.BUGGY_SAFARI_ITERATORS,ys=qc("iterator"),pr="keys",di="values",mr="entries",Wc=function(){return this},Qc=function(i,e,t,s,a,n,o){Hc(t,e,s);var l=function(b){if(b===a&&f)return f;if(!ui&&b in h)return h[b];switch(b){case pr:return function(){return new t(this,b)};case di:return function(){return new t(this,b)};case mr:return function(){return new t(this,b)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,h=i.prototype,d=h[ys]||h["@@iterator"]||a&&h[a],f=!ui&&d||l(a),p=e=="Array"&&h.entries||d,v,m,S;if(p&&(v=Gc(p.call(new i)),v!==Object.prototype&&v.next&&(Yc(v,c,!0,!0),fr[c]=Wc)),zc&&a==di&&d&&d.name!==di&&(u=!0,f=function(){return jc(d,this)}),a)if(m={values:l(di),keys:n?f:l(pr),entries:l(mr)},o)for(S in m)(ui||u||!(S in h))&&hr(h,S,m[S]);else Uc({target:e,proto:!0,forced:ui||u},m);return o&&h[ys]!==f&&hr(h,ys,f,{name:a}),fr[e]=f,m},Kc=function(i,e){return{value:i,done:e}},Jc=zt,vr=xt,jn=_u;_t.f;var Xc=Qc,ci=Kc,Hn="Array Iterator",Zc=jn.set,eh=jn.getterFor(Hn);Xc(Array,"Array",function(i,e){Zc(this,{type:Hn,target:Jc(i),index:0,kind:e})},function(){var i=eh(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,ci(void 0,!0)):t=="keys"?ci(s,!1):t=="values"?ci(e[s],!1):ci([s,e[s]],!1)},"values");vr.Arguments=vr.Array;var th=Te,ih=xt,sh=th("iterator"),ah=Array.prototype,rh=function(i){return i!==void 0&&(ih.Array===i||ah[sh]===i)},nh=Vi,Sr=Ni,oh=Ii,lh=xt,uh=Te,dh=uh("iterator"),Gn=function(i){if(!oh(i))return Sr(i,dh)||Sr(i,"@@iterator")||lh[nh(i)]},ch=Be,hh=oa,fh=nt,ph=na,mh=Gn,vh=TypeError,Sh=function(i,e){var t=arguments.length<2?mh(i):e;if(hh(t))return fh(ch(t,i));throw vh(ph(i)+" is not iterable")},bh=Be,br=nt,gh=Ni,yh=function(i,e,t){var s,a;br(i);try{if(s=gh(i,"return"),!s){if(e==="throw")throw t;return t}s=bh(s,i)}catch(n){a=!0,s=n}if(e==="throw")throw t;if(a)throw s;return br(s),t},Th=Pn,Eh=Be,$h=nt,kh=na,Ah=rh,wh=fa,gr=ra,Ph=Sh,Ch=Gn,yr=yh,Lh=TypeError,Ei=function(i,e){this.stopped=i,this.result=e},Tr=Ei.prototype,Dh=function(i,e,t){var s=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),c=Th(e,s),u,h,d,f,p,v,m,S=function(y){return u&&yr(u,"normal",y),new Ei(!0,y)},b=function(y){return a?($h(y),l?c(y[0],y[1],S):c(y[0],y[1])):l?c(y,S):c(y)};if(n)u=i.iterator;else if(o)u=i;else{if(h=Ch(i),!h)throw Lh(kh(i)+" is not iterable");if(Ah(h)){for(d=0,f=wh(i);f>d;d++)if(p=b(i[d]),p&&gr(Tr,p))return p;return new Ei(!1)}u=Ph(i,h)}for(v=n?i.next:u.next;!(m=Eh(v,u)).done;){try{p=b(m.value)}catch(y){yr(u,"throw",y)}if(typeof p=="object"&&p&&gr(Tr,p))return p}return new Ei(!1)},xh=la,_h=_t,Rh=Mi,Ih=function(i,e,t){var s=xh(e);s in i?_h.f(i,s,Rh(0,t)):i[s]=t},Nh=Bi,Oh=Dh,Mh=Ih;Nh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Oh(e,function(s,a){Mh(t,s,a)},{AS_ENTRIES:!0}),t}});var Bh=sa,Vh=Bh.Object.fromEntries,Fh={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},Uh=Fh,jh=ye,Hh=Vi,Gh=Wt,Er=xt,Yh=Te,$r=Yh("toStringTag");for(var Ts in Uh){var kr=jh[Ts],Es=kr&&kr.prototype;Es&&Hh(Es)!==$r&&Gh(Es,$r,Ts),Er[Ts]=Er.Array}var qh=Vh,zh=qh,Wh=zh,Qh=Wh,Pi=ta(Qh),ee;(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"})(ee||(ee={}));var ge=(i,e=0,t=ee.OFFSET_P)=>{switch(t){case ee.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ee.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ee.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:r.assertNever(t)}return i};const Ar=(i,e)=>{var t;switch(e){case ee.OFFSET_P:return NaN;case ee.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ee.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:r.assertNever(e)}};var P=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class J{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(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||r.isNonNullable(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 Kh=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(i)}};var x;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const Jh=5,Xh=5,Zh=500,wr=7e3;class ef{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new J(x.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===I.Requested&&s!==x.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case x.PLAYING:case x.PAUSED:case x.READY:break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:r.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case x.PLAYING:break;case x.PAUSED:this.videoState.startTransitionTo(x.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case x.READY:this.videoState.startTransitionTo(x.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:r.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case x.PLAYING:this.videoState.startTransitionTo(x.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case x.PAUSED:break;case x.READY:this.videoState.startTransitionTo(x.PAUSED),this.videoState.setState(x.PAUSED);break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:r.assertNever(s)}break}default:r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Kh(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 r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Zh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===I.Applying||Math.abs(l-n)>Jh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.value,l=this.params.output.isBuffering$.getValue(),c=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==c&&this.params.output.isBuffering$.next(c),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Xh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const s=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(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(x.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(x.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.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:I.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)===x.PAUSED||e===x.PLAYING)&&(this.videoState.setState(x.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===x.PLAYING||e===x.PAUSED)&&(this.videoState.setState(x.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===x.READY&&this.videoState.setState(x.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==x.STOPPED&&this.videoState.setState(x.STOPPED)}handleRemoteVolumeChange(e){var t,s;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(s=e.muted)!==null&&s!==void 0?s:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}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 a,n,o;switch(e){case exports.VideoFormat.MPEG:{const h=s[e];r.assertNonNullable(h);const d=r.getHighestQuality(Object.keys(h));r.assertNonNullable(d);const f=h[d];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const h=s[e];r.assertNonNullable(h),a=h.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const h=s[e];r.assertNonNullable(h),a=h.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const h=s[e];r.assertNonNullable(h),a=h.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const h=s[e];r.assertNonNullable(h),a=ge(h.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const h="Unsupported format for Chromecast",d=new Error(h);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:h,thrown:d}),d}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:u}=this.params.meta;return r.isNonNullable(c)&&(l.metadata.title=c),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===I.Applying||s.state===I.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((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(wr).subscribe(()=>n(`timeout(${wr})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===I.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const ma=i=>{i.removeAttribute("src"),i.load()},tf=i=>{try{i.pause(),i.playbackRate=0,ma(i),i.remove()}catch(e){console.error(e)}};class sf{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 Qs=window.WeakMap?new WeakMap:new sf,ot=i=>{let e=i.querySelector("video");const t=!!e;return e?ma(e):(e=document.createElement("video"),i.appendChild(e)),Qs.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},lt=i=>{const e=Qs.get(i);Qs.delete(i),e?ma(i):tf(i)},_e=(i,e,t,{equal:s=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=i.getState(),l=e(),c=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(h=>{const d=i.getState();s(h,d)&&i.setState(h)},n)),s(l,o)||(t(o),c&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(h=>{t(h.to),c&&i.setState(h.to)},n)),u},Kt=(i,e,t)=>_e(e,()=>i.loop,s=>{r.isNonNullable(s)&&(i.loop=s)},{onError:t}),ut=(i,e,t,s)=>_e(e,()=>({muted:i.muted,volume:i.volume}),a=>{r.isNonNullable(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),Rt=(i,e,t,s)=>_e(e,()=>i.playbackRate,a=>{r.isNonNullable(a)&&(i.playbackRate=a)},{changed$:t,onError:s}),af=i=>["__",i.language,i.label].join("|"),rf=(i,e)=>{if(i.id===e)return!0;const[t,s,a]=e.split("|");return i.language===s&&i.label===a};class qe{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};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(_e(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(_e(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(_e(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(_e(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),r.filterChanged((s,a)=>s.length===a.length&&s.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),r.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),r.filterChanged()).subscribe(this.current$));const t=s=>{var a,n;return this.applyCueSettings((n=(a=s.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(s=>{var a,n;(a=s.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var c,u,h,d,f;const p=(u=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((d=(h=l.target)===null||h===void 0?void 0:h.cues)!==null&&d!==void 0?d:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(s=>{var a;(a=s.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const a=s;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(qe.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:a,label:n}=e,o=e.id?e.id:af(e),l=this.externalTracks.has(o),c=o.includes("auto");return l?{id:o,type:"external",isAuto:c,language:a,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:c,language:a,label:n,url:(s=this.internalTracks.get(o))===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:a,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(a=>a.id===s)).forEach(([,s])=>this.detach(s))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!rf(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){r.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(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 va{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 Yn=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},Pr=i=>{const e=Yn(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},nf=i=>{const e=Yn(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},of=3;var lf=(i,e,t=of)=>{let s=0,a=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,a=l,!t)return{from:s,to:a};for(let c=n-1;c>=0;c--)i.end(c)+t>=s&&(s=i.start(c));for(let c=n+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:s,to:a}};const dt=i=>{const e=T=>r.fromEvent(i,T).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=r.merge(...t.map(T=>r.fromEvent(i,T))).pipe(r.map(T=>T.type==="ended"?i.readyState<2:i.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(i,"progress"),r.fromEvent(i,"timeupdate")).pipe(r.map(()=>lf(i.buffered,i.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),l=r.fromEvent(i,"volumechange").pipe(r.map(()=>({muted:i.muted,volume:i.volume}))),c=r.fromEvent(i,"ratechange").pipe(r.map(()=>i.playbackRate)),u=r.fromEvent(i,"error").pipe(r.filter(()=>!!(i.error||i.played.length)),r.map(()=>{var T;const E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(T=i.error)!==null&&T!==void 0?T:void 0}})),h=r.fromEvent(i,"timeupdate").pipe(r.map(()=>i.currentTime)),d=new r.Subject,f=.3;let p;h.subscribe(T=>{i.loop&&r.isNonNullable(p)&&r.isNonNullable(T)&&p>=i.duration-f&&T<=f&&d.next(p),p=T});const v=r.fromEvent(i,"enterpictureinpicture"),m=r.fromEvent(i,"leavepictureinpicture"),S=new r.ValueSubject(nf(i));v.subscribe(()=>S.next(!0)),m.subscribe(()=>S.next(!1));const b=new r.ValueSubject(Pr(i));return r.fromEvent(i,"fullscreenchange").pipe(r.map(()=>Pr(i))).subscribe(b),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!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$:h,durationChange$:r.fromEvent(i,"durationchange").pipe(r.map(()=>i.duration)),isBuffering$:s,currentBuffer$:a,volumeState$:l,playbackRateState$:c,inPiP$:S,inFullscreen$:b}};var Fi=i=>{switch(i){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}},uf=Bi,df=Oi,cf=fa,hf=ha;uf({target:"Array",proto:!0},{at:function(e){var t=df(this),s=cf(t),a=hf(e),n=a>=0?a:s+a;return n<0||n>=s?void 0:t[n]}});var ff=aa,qn=ff,pf=qn,mf=pf("Array","at"),vf=mf,Sf=vf,bf=Sf,gf=bf,xe=ta(gf);let Sa=!1,Re={};const yf=i=>{Sa=i},Tf=()=>{Re={}},Ef=i=>{i(Re)},hi=(i,e)=>{var t;Sa&&(Re.meta=(t=Re.meta)!==null&&t!==void 0?t:{},Re.meta[i]=e)};class we{constructor(e){this.name=e}next(e){var t,s;if(!Sa)return;Re.series=(t=Re.series)!==null&&t!==void 0?t:{};const a=(s=Re.series[this.name])!==null&&s!==void 0?s:[];a.push([Date.now(),e]),Re.series[this.name]=a}}var tt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(tt||(tt={}));const $f=new we("best_bitrate"),kf=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class Af{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const wf='Assertion "ABR Tracks is empty array" failed',Ui=(i,{container:e,throughput:t,tuning:s,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:c,history:u,droppedVideoMaxQualityLimit:h,abrLogger:d})=>{var f,p,v,m,S;r.assertNotEmptyArray(i,wf);const b=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*s.containerSizeFactor,height:e.height*b*s.containerSizeFactor},T=y&&r.videoSizeToQuality(y),E=s.considerPlaybackRate&&r.isNonNullable(l)?l:1,$=i.filter(L=>!r.isInvariantQuality(L.quality)).sort((L,A)=>r.isHigher(L.quality,A.quality)?-1:1),N=(p=xe($,-1))===null||p===void 0?void 0:p.quality,O=(v=xe($,0))===null||v===void 0?void 0:v.quality,V=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&r.isLower(a.max,a.min)||r.isNonNullable(a.min)&&O&&r.isHigher(a.min,O)||r.isNonNullable(a.max)&&N&&r.isLower(a.max,N),R=E*kf(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),F={},C=$.filter(L=>(T?r.isLower(L.quality,T):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(L.bitrate)?t-n>=L.bitrate*R:!0)?s.lazyQualitySwitch&&r.isNonNullable(s.minBufferToSwitchUp)&&c&&!r.isInvariantQuality(c.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&r.isHigher(L.quality,c.quality)?(F[L.quality]=tt.Buffer,!1):!!h&&r.isHigherOrEqual(L.quality,h)?(F[L.quality]=tt.DroppedFramesLimit,!1):V||(r.isNullable(a.max)||r.isLowerOrEqual(L.quality,a.max))&&(r.isNullable(a.min)||r.isHigherOrEqual(L.quality,a.min))?!0:(F[L.quality]=tt.FitsQualityLimits,!1):(F[L.quality]=tt.FitsThroughput,!1):(F[L.quality]=tt.FitsContainer,!1))[0];C&&C.bitrate&&$f.next(C.bitrate);const w=(m=C!=null?C:$[Math.ceil(($.length-1)/2)])!==null&&m!==void 0?m:i[0];w.quality!==((S=u==null?void 0:u.last)===null||S===void 0?void 0:S.quality)&&d({message:`
6
+ "use strict";var ub=Object.create;var ra=Object.defineProperty;var lb=Object.getOwnPropertyDescriptor;var cb=Object.getOwnPropertyNames;var db=Object.getPrototypeOf,pb=Object.prototype.hasOwnProperty;var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),hb=(i,e)=>{for(var t in e)ra(i,t,{get:e[t],enumerable:!0})},fu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of cb(e))!pb.call(i,a)&&a!==t&&ra(i,a,{get:()=>e[a],enumerable:!(r=lb(e,a))||r.enumerable});return i};var Ne=(i,e,t)=>(t=i!=null?ub(db(i)):{},fu(e||!i||!i.__esModule?ra(t,"default",{value:i,enumerable:!0}):t,i)),fb=i=>fu(ra({},"__esModule",{value:!0}),i);var we=b(($P,bu)=>{"use strict";bu.exports=function(i){try{return!!i()}catch(e){return!0}}});var Or=b((CP,gu)=>{"use strict";var bb=we();gu.exports=!bb(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ve=b((DP,yu)=>{"use strict";var vu=Or(),Su=Function.prototype,$s=Su.call,gb=vu&&Su.bind.bind($s,$s);yu.exports=vu?gb:function(i){return function(){return $s.apply(i,arguments)}}});var nr=b((MP,Iu)=>{"use strict";var Tu=ve(),vb=Tu({}.toString),Sb=Tu("".slice);Iu.exports=function(i){return Sb(vb(i),8,-1)}});var xu=b((OP,Eu)=>{"use strict";var yb=ve(),Tb=we(),Ib=nr(),Cs=Object,Eb=yb("".split);Eu.exports=Tb(function(){return!Cs("z").propertyIsEnumerable(0)})?function(i){return Ib(i)=="String"?Eb(i,""):Cs(i)}:Cs});var or=b((BP,Pu)=>{"use strict";Pu.exports=function(i){return i==null}});var na=b((VP,wu)=>{"use strict";var xb=or(),Pb=TypeError;wu.exports=function(i){if(xb(i))throw Pb("Can't call method on "+i);return i}});var ur=b((_P,ku)=>{"use strict";var wb=xu(),kb=na();ku.exports=function(i){return wb(kb(i))}});var Ds=b((NP,Au)=>{"use strict";Au.exports=function(){}});var Ot=b((FP,Ru)=>{"use strict";Ru.exports={}});var ue=b((Lu,$u)=>{"use strict";var oa=function(i){return i&&i.Math==Math&&i};$u.exports=oa(typeof globalThis=="object"&&globalThis)||oa(typeof window=="object"&&window)||oa(typeof self=="object"&&self)||oa(typeof global=="object"&&global)||function(){return this}()||Lu||Function("return this")()});var Os=b((qP,Cu)=>{"use strict";var Ms=typeof document=="object"&&document.all,Ab=typeof Ms=="undefined"&&Ms!==void 0;Cu.exports={all:Ms,IS_HTMLDDA:Ab}});var te=b((UP,Mu)=>{"use strict";var Du=Os(),Rb=Du.all;Mu.exports=Du.IS_HTMLDDA?function(i){return typeof i=="function"||i===Rb}:function(i){return typeof i=="function"}});var Vu=b((HP,Bu)=>{"use strict";var Lb=ue(),$b=te(),Ou=Lb.WeakMap;Bu.exports=$b(Ou)&&/native code/.test(String(Ou))});var Qe=b((jP,Fu)=>{"use strict";var _u=te(),Nu=Os(),Cb=Nu.all;Fu.exports=Nu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:_u(i)||i===Cb}:function(i){return typeof i=="object"?i!==null:_u(i)}});var ze=b((GP,qu)=>{"use strict";var Db=we();qu.exports=!Db(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var ua=b((YP,Hu)=>{"use strict";var Mb=ue(),Uu=Qe(),Bs=Mb.document,Ob=Uu(Bs)&&Uu(Bs.createElement);Hu.exports=function(i){return Ob?Bs.createElement(i):{}}});var Vs=b((WP,ju)=>{"use strict";var Bb=ze(),Vb=we(),_b=ua();ju.exports=!Bb&&!Vb(function(){return Object.defineProperty(_b("div"),"a",{get:function(){return 7}}).a!=7})});var _s=b((QP,Gu)=>{"use strict";var Nb=ze(),Fb=we();Gu.exports=Nb&&Fb(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Fe=b((zP,Yu)=>{"use strict";var qb=Qe(),Ub=String,Hb=TypeError;Yu.exports=function(i){if(qb(i))return i;throw Hb(Ub(i)+" is not an object")}});var Se=b((KP,Wu)=>{"use strict";var jb=Or(),la=Function.prototype.call;Wu.exports=jb?la.bind(la):function(){return la.apply(la,arguments)}});var ca=b((JP,Qu)=>{"use strict";Qu.exports={}});var rt=b((XP,Ku)=>{"use strict";var Ns=ca(),Fs=ue(),Gb=te(),zu=function(i){return Gb(i)?i:void 0};Ku.exports=function(i,e){return arguments.length<2?zu(Ns[i])||zu(Fs[i]):Ns[i]&&Ns[i][e]||Fs[i]&&Fs[i][e]}});var Br=b((ZP,Ju)=>{"use strict";var Yb=ve();Ju.exports=Yb({}.isPrototypeOf)});var Vr=b((ew,Xu)=>{"use strict";Xu.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var Us=b((tw,al)=>{"use strict";var il=ue(),qs=Vr(),Zu=il.process,el=il.Deno,tl=Zu&&Zu.versions||el&&el.version,rl=tl&&tl.v8,qe,da;rl&&(qe=rl.split("."),da=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!da&&qs&&(qe=qs.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=qs.match(/Chrome\/(\d+)/),qe&&(da=+qe[1])));al.exports=da});var Hs=b((rw,nl)=>{"use strict";var sl=Us(),Wb=we(),Qb=ue(),zb=Qb.String;nl.exports=!!Object.getOwnPropertySymbols&&!Wb(function(){var i=Symbol();return!zb(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&sl&&sl<41})});var js=b((iw,ol)=>{"use strict";var Kb=Hs();ol.exports=Kb&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Gs=b((aw,ul)=>{"use strict";var Jb=rt(),Xb=te(),Zb=Br(),eg=js(),tg=Object;ul.exports=eg?function(i){return typeof i=="symbol"}:function(i){var e=Jb("Symbol");return Xb(e)&&Zb(e.prototype,tg(i))}});var _r=b((sw,ll)=>{"use strict";var rg=String;ll.exports=function(i){try{return rg(i)}catch(e){return"Object"}}});var it=b((nw,cl)=>{"use strict";var ig=te(),ag=_r(),sg=TypeError;cl.exports=function(i){if(ig(i))return i;throw sg(ag(i)+" is not a function")}});var Nr=b((ow,dl)=>{"use strict";var ng=it(),og=or();dl.exports=function(i,e){var t=i[e];return og(t)?void 0:ng(t)}});var hl=b((uw,pl)=>{"use strict";var Ys=Se(),Ws=te(),Qs=Qe(),ug=TypeError;pl.exports=function(i,e){var t,r;if(e==="string"&&Ws(t=i.toString)&&!Qs(r=Ys(t,i))||Ws(t=i.valueOf)&&!Qs(r=Ys(t,i))||e!=="string"&&Ws(t=i.toString)&&!Qs(r=Ys(t,i)))return r;throw ug("Can't convert object to primitive value")}});var Ue=b((lw,fl)=>{"use strict";fl.exports=!0});var gl=b((cw,bl)=>{"use strict";var ml=ue(),lg=Object.defineProperty;bl.exports=function(i,e){try{lg(ml,i,{value:e,configurable:!0,writable:!0})}catch(t){ml[i]=e}return e}});var pa=b((dw,Sl)=>{"use strict";var cg=ue(),dg=gl(),vl="__core-js_shared__",pg=cg[vl]||dg(vl,{});Sl.exports=pg});var zs=b((pw,Tl)=>{"use strict";var hg=Ue(),yl=pa();(Tl.exports=function(i,e){return yl[i]||(yl[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:hg?"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 Fr=b((hw,Il)=>{"use strict";var fg=na(),mg=Object;Il.exports=function(i){return mg(fg(i))}});var He=b((fw,El)=>{"use strict";var bg=ve(),gg=Fr(),vg=bg({}.hasOwnProperty);El.exports=Object.hasOwn||function(e,t){return vg(gg(e),t)}});var Ks=b((mw,xl)=>{"use strict";var Sg=ve(),yg=0,Tg=Math.random(),Ig=Sg(1 .toString);xl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Ig(++yg+Tg,36)}});var de=b((bw,wl)=>{"use strict";var Eg=ue(),xg=zs(),Pl=He(),Pg=Ks(),wg=Hs(),kg=js(),lr=Eg.Symbol,Js=xg("wks"),Ag=kg?lr.for||lr:lr&&lr.withoutSetter||Pg;wl.exports=function(i){return Pl(Js,i)||(Js[i]=wg&&Pl(lr,i)?lr[i]:Ag("Symbol."+i)),Js[i]}});var Ll=b((gw,Rl)=>{"use strict";var Rg=Se(),kl=Qe(),Al=Gs(),Lg=Nr(),$g=hl(),Cg=de(),Dg=TypeError,Mg=Cg("toPrimitive");Rl.exports=function(i,e){if(!kl(i)||Al(i))return i;var t=Lg(i,Mg),r;if(t){if(e===void 0&&(e="default"),r=Rg(t,i,e),!kl(r)||Al(r))return r;throw Dg("Can't convert object to primitive value")}return e===void 0&&(e="number"),$g(i,e)}});var ha=b((vw,$l)=>{"use strict";var Og=Ll(),Bg=Gs();$l.exports=function(i){var e=Og(i,"string");return Bg(e)?e:e+""}});var Bt=b(Dl=>{"use strict";var Vg=ze(),_g=Vs(),Ng=_s(),fa=Fe(),Cl=ha(),Fg=TypeError,Xs=Object.defineProperty,qg=Object.getOwnPropertyDescriptor,Zs="enumerable",en="configurable",tn="writable";Dl.f=Vg?Ng?function(e,t,r){if(fa(e),t=Cl(t),fa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&tn in r&&!r[tn]){var a=qg(e,t);a&&a[tn]&&(e[t]=r.value,r={configurable:en in r?r[en]:a[en],enumerable:Zs in r?r[Zs]:a[Zs],writable:!1})}return Xs(e,t,r)}:Xs:function(e,t,r){if(fa(e),t=Cl(t),fa(r),_g)try{return Xs(e,t,r)}catch(a){}if("get"in r||"set"in r)throw Fg("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var qr=b((yw,Ml)=>{"use strict";Ml.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Vt=b((Tw,Ol)=>{"use strict";var Ug=ze(),Hg=Bt(),jg=qr();Ol.exports=Ug?function(i,e,t){return Hg.f(i,e,jg(1,t))}:function(i,e,t){return i[e]=t,i}});var ma=b((Iw,Vl)=>{"use strict";var Gg=zs(),Yg=Ks(),Bl=Gg("keys");Vl.exports=function(i){return Bl[i]||(Bl[i]=Yg(i))}});var ba=b((Ew,_l)=>{"use strict";_l.exports={}});var nn=b((xw,ql)=>{"use strict";var Wg=Vu(),Fl=ue(),Qg=Qe(),zg=Vt(),rn=He(),an=pa(),Kg=ma(),Jg=ba(),Nl="Object already initialized",sn=Fl.TypeError,Xg=Fl.WeakMap,ga,Ur,va,Zg=function(i){return va(i)?Ur(i):ga(i,{})},ev=function(i){return function(e){var t;if(!Qg(e)||(t=Ur(e)).type!==i)throw sn("Incompatible receiver, "+i+" required");return t}};Wg||an.state?(je=an.state||(an.state=new Xg),je.get=je.get,je.has=je.has,je.set=je.set,ga=function(i,e){if(je.has(i))throw sn(Nl);return e.facade=i,je.set(i,e),e},Ur=function(i){return je.get(i)||{}},va=function(i){return je.has(i)}):(_t=Kg("state"),Jg[_t]=!0,ga=function(i,e){if(rn(i,_t))throw sn(Nl);return e.facade=i,zg(i,_t,e),e},Ur=function(i){return rn(i,_t)?i[_t]:{}},va=function(i){return rn(i,_t)});var je,_t;ql.exports={set:ga,get:Ur,has:va,enforce:Zg,getterFor:ev}});var on=b((Pw,Gl)=>{"use strict";var tv=Or(),jl=Function.prototype,Ul=jl.apply,Hl=jl.call;Gl.exports=typeof Reflect=="object"&&Reflect.apply||(tv?Hl.bind(Ul):function(){return Hl.apply(Ul,arguments)})});var un=b((ww,Yl)=>{"use strict";var rv=nr(),iv=ve();Yl.exports=function(i){if(rv(i)==="Function")return iv(i)}});var Kl=b(zl=>{"use strict";var Wl={}.propertyIsEnumerable,Ql=Object.getOwnPropertyDescriptor,av=Ql&&!Wl.call({1:2},1);zl.f=av?function(e){var t=Ql(this,e);return!!t&&t.enumerable}:Wl});var ln=b(Xl=>{"use strict";var sv=ze(),nv=Se(),ov=Kl(),uv=qr(),lv=ur(),cv=ha(),dv=He(),pv=Vs(),Jl=Object.getOwnPropertyDescriptor;Xl.f=sv?Jl:function(e,t){if(e=lv(e),t=cv(t),pv)try{return Jl(e,t)}catch(r){}if(dv(e,t))return uv(!nv(ov.f,e,t),e[t])}});var cn=b((Rw,Zl)=>{"use strict";var hv=we(),fv=te(),mv=/#|\.prototype\./,Hr=function(i,e){var t=gv[bv(i)];return t==Sv?!0:t==vv?!1:fv(e)?hv(e):!!e},bv=Hr.normalize=function(i){return String(i).replace(mv,".").toLowerCase()},gv=Hr.data={},vv=Hr.NATIVE="N",Sv=Hr.POLYFILL="P";Zl.exports=Hr});var jr=b((Lw,tc)=>{"use strict";var ec=un(),yv=it(),Tv=Or(),Iv=ec(ec.bind);tc.exports=function(i,e){return yv(i),e===void 0?i:Tv?Iv(i,e):function(){return i.apply(e,arguments)}}});var $e=b(($w,ic)=>{"use strict";var Sa=ue(),Ev=on(),xv=un(),Pv=te(),wv=ln().f,kv=cn(),cr=ca(),Av=jr(),dr=Vt(),rc=He(),Rv=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 Ev(i,this,arguments)};return e.prototype=i.prototype,e};ic.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Sa:a?Sa[t]:(Sa[t]||{}).prototype,o=r?cr:cr[t]||dr(cr,t,{})[t],l=o.prototype,u,c,d,p,m,f,g,S,y;for(p in e)u=kv(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&rc(n,p),f=o[p],c&&(i.dontCallGetSet?(y=wv(n,p),g=y&&y.value):g=n[p]),m=c&&g?g:e[p],!(c&&typeof f==typeof m)&&(i.bind&&c?S=Av(m,Sa):i.wrap&&c?S=Rv(m):s&&Pv(m)?S=xv(m):S=m,(i.sham||m&&m.sham||f&&f.sham)&&dr(S,"sham",!0),dr(o,p,S),s&&(d=t+"Prototype",rc(cr,d)||dr(cr,d,{}),dr(cr[d],p,m),i.real&&l&&(u||!l[p])&&dr(l,p,m)))}});var nc=b((Cw,sc)=>{"use strict";var dn=ze(),Lv=He(),ac=Function.prototype,$v=dn&&Object.getOwnPropertyDescriptor,pn=Lv(ac,"name"),Cv=pn&&function(){}.name==="something",Dv=pn&&(!dn||dn&&$v(ac,"name").configurable);sc.exports={EXISTS:pn,PROPER:Cv,CONFIGURABLE:Dv}});var uc=b((Dw,oc)=>{"use strict";var Mv=Math.ceil,Ov=Math.floor;oc.exports=Math.trunc||function(e){var t=+e;return(t>0?Ov:Mv)(t)}});var ya=b((Mw,lc)=>{"use strict";var Bv=uc();lc.exports=function(i){var e=+i;return e!==e||e===0?0:Bv(e)}});var dc=b((Ow,cc)=>{"use strict";var Vv=ya(),_v=Math.max,Nv=Math.min;cc.exports=function(i,e){var t=Vv(i);return t<0?_v(t+e,0):Nv(t,e)}});var hc=b((Bw,pc)=>{"use strict";var Fv=ya(),qv=Math.min;pc.exports=function(i){return i>0?qv(Fv(i),9007199254740991):0}});var Ta=b((Vw,fc)=>{"use strict";var Uv=hc();fc.exports=function(i){return Uv(i.length)}});var gc=b((_w,bc)=>{"use strict";var Hv=ur(),jv=dc(),Gv=Ta(),mc=function(i){return function(e,t,r){var a=Hv(e),s=Gv(a),n=jv(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}};bc.exports={includes:mc(!0),indexOf:mc(!1)}});var yc=b((Nw,Sc)=>{"use strict";var Yv=ve(),hn=He(),Wv=ur(),Qv=gc().indexOf,zv=ba(),vc=Yv([].push);Sc.exports=function(i,e){var t=Wv(i),r=0,a=[],s;for(s in t)!hn(zv,s)&&hn(t,s)&&vc(a,s);for(;e.length>r;)hn(t,s=e[r++])&&(~Qv(a,s)||vc(a,s));return a}});var fn=b((Fw,Tc)=>{"use strict";Tc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ec=b((qw,Ic)=>{"use strict";var Kv=yc(),Jv=fn();Ic.exports=Object.keys||function(e){return Kv(e,Jv)}});var Pc=b(xc=>{"use strict";var Xv=ze(),Zv=_s(),eS=Bt(),tS=Fe(),rS=ur(),iS=Ec();xc.f=Xv&&!Zv?Object.defineProperties:function(e,t){tS(e);for(var r=rS(t),a=iS(t),s=a.length,n=0,o;s>n;)eS.f(e,o=a[n++],r[o]);return e}});var mn=b((Hw,wc)=>{"use strict";var aS=rt();wc.exports=aS("document","documentElement")});var Sn=b((jw,Dc)=>{"use strict";var sS=Fe(),nS=Pc(),kc=fn(),oS=ba(),uS=mn(),lS=ua(),cS=ma(),Ac=">",Rc="<",gn="prototype",vn="script",$c=cS("IE_PROTO"),bn=function(){},Cc=function(i){return Rc+vn+Ac+i+Rc+"/"+vn+Ac},Lc=function(i){i.write(Cc("")),i.close();var e=i.parentWindow.Object;return i=null,e},dS=function(){var i=lS("iframe"),e="java"+vn+":",t;return i.style.display="none",uS.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Cc("document.F=Object")),t.close(),t.F},Ia,Ea=function(){try{Ia=new ActiveXObject("htmlfile")}catch(e){}Ea=typeof document!="undefined"?document.domain&&Ia?Lc(Ia):dS():Lc(Ia);for(var i=kc.length;i--;)delete Ea[gn][kc[i]];return Ea()};oS[$c]=!0;Dc.exports=Object.create||function(e,t){var r;return e!==null?(bn[gn]=sS(e),r=new bn,bn[gn]=null,r[$c]=e):r=Ea(),t===void 0?r:nS.f(r,t)}});var Oc=b((Gw,Mc)=>{"use strict";var pS=we();Mc.exports=!pS(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Tn=b((Yw,Vc)=>{"use strict";var hS=He(),fS=te(),mS=Fr(),bS=ma(),gS=Oc(),Bc=bS("IE_PROTO"),yn=Object,vS=yn.prototype;Vc.exports=gS?yn.getPrototypeOf:function(i){var e=mS(i);if(hS(e,Bc))return e[Bc];var t=e.constructor;return fS(t)&&e instanceof t?t.prototype:e instanceof yn?vS:null}});var pr=b((Ww,_c)=>{"use strict";var SS=Vt();_c.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:SS(i,e,t),i}});var Pn=b((Qw,qc)=>{"use strict";var yS=we(),TS=te(),IS=Qe(),ES=Sn(),Nc=Tn(),xS=pr(),PS=de(),wS=Ue(),xn=PS("iterator"),Fc=!1,at,In,En;[].keys&&(En=[].keys(),"next"in En?(In=Nc(Nc(En)),In!==Object.prototype&&(at=In)):Fc=!0);var kS=!IS(at)||yS(function(){var i={};return at[xn].call(i)!==i});kS?at={}:wS&&(at=ES(at));TS(at[xn])||xS(at,xn,function(){return this});qc.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:Fc}});var xa=b((zw,Hc)=>{"use strict";var AS=de(),RS=AS("toStringTag"),Uc={};Uc[RS]="z";Hc.exports=String(Uc)==="[object z]"});var hr=b((Kw,jc)=>{"use strict";var LS=xa(),$S=te(),Pa=nr(),CS=de(),DS=CS("toStringTag"),MS=Object,OS=Pa(function(){return arguments}())=="Arguments",BS=function(i,e){try{return i[e]}catch(t){}};jc.exports=LS?Pa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=BS(e=MS(i),DS))=="string"?t:OS?Pa(e):(r=Pa(e))=="Object"&&$S(e.callee)?"Arguments":r}});var Yc=b((Jw,Gc)=>{"use strict";var VS=xa(),_S=hr();Gc.exports=VS?{}.toString:function(){return"[object "+_S(this)+"]"}});var wa=b((Xw,Qc)=>{"use strict";var NS=xa(),FS=Bt().f,qS=Vt(),US=He(),HS=Yc(),jS=de(),Wc=jS("toStringTag");Qc.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;US(a,Wc)||FS(a,Wc,{configurable:!0,value:e}),r&&!NS&&qS(a,"toString",HS)}}});var Kc=b((Zw,zc)=>{"use strict";var GS=Pn().IteratorPrototype,YS=Sn(),WS=qr(),QS=wa(),zS=Ot(),KS=function(){return this};zc.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=YS(GS,{next:WS(+!r,t)}),QS(i,a,!1,!0),zS[a]=KS,i}});var Xc=b((ek,Jc)=>{"use strict";var JS=ve(),XS=it();Jc.exports=function(i,e,t){try{return JS(XS(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var ed=b((tk,Zc)=>{"use strict";var ZS=te(),ey=String,ty=TypeError;Zc.exports=function(i){if(typeof i=="object"||ZS(i))return i;throw ty("Can't set "+ey(i)+" as a prototype")}});var wn=b((rk,td)=>{"use strict";var ry=Xc(),iy=Fe(),ay=ed();td.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=ry(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return iy(a),ay(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var pd=b((ik,dd)=>{"use strict";var sy=$e(),ny=Se(),ka=Ue(),ld=nc(),oy=te(),uy=Kc(),rd=Tn(),id=wn(),ly=wa(),cy=Vt(),kn=pr(),dy=de(),ad=Ot(),cd=Pn(),py=ld.PROPER,hy=ld.CONFIGURABLE,sd=cd.IteratorPrototype,Aa=cd.BUGGY_SAFARI_ITERATORS,Gr=dy("iterator"),nd="keys",Yr="values",od="entries",ud=function(){return this};dd.exports=function(i,e,t,r,a,s,n){uy(t,e,r);var o=function(y){if(y===a&&p)return p;if(!Aa&&y in c)return c[y];switch(y){case nd:return function(){return new t(this,y)};case Yr:return function(){return new t(this,y)};case od:return function(){return new t(this,y)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Gr]||c["@@iterator"]||a&&c[a],p=!Aa&&d||o(a),m=e=="Array"&&c.entries||d,f,g,S;if(m&&(f=rd(m.call(new i)),f!==Object.prototype&&f.next&&(!ka&&rd(f)!==sd&&(id?id(f,sd):oy(f[Gr])||kn(f,Gr,ud)),ly(f,l,!0,!0),ka&&(ad[l]=ud))),py&&a==Yr&&d&&d.name!==Yr&&(!ka&&hy?cy(c,"name",Yr):(u=!0,p=function(){return ny(d,this)})),a)if(g={values:o(Yr),keys:s?p:o(nd),entries:o(od)},n)for(S in g)(Aa||u||!(S in c))&&kn(c,S,g[S]);else sy({target:e,proto:!0,forced:Aa||u},g);return(!ka||n)&&c[Gr]!==p&&kn(c,Gr,p,{name:a}),ad[e]=p,g}});var fd=b((ak,hd)=>{"use strict";hd.exports=function(i,e){return{value:i,done:e}}});var Rn=b((sk,Sd)=>{"use strict";var fy=ur(),An=Ds(),md=Ot(),gd=nn(),my=Bt().f,by=pd(),Ra=fd(),gy=Ue(),vy=ze(),vd="Array Iterator",Sy=gd.set,yy=gd.getterFor(vd);Sd.exports=by(Array,"Array",function(i,e){Sy(this,{type:vd,target:fy(i),index:0,kind:e})},function(){var i=yy(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Ra(void 0,!0)):t=="keys"?Ra(r,!1):t=="values"?Ra(e[r],!1):Ra([r,e[r]],!1)},"values");var bd=md.Arguments=md.Array;An("keys");An("values");An("entries");if(!gy&&vy&&bd.name!=="values")try{my(bd,"name",{value:"values"})}catch(i){}});var Td=b((nk,yd)=>{"use strict";var Ty=de(),Iy=Ot(),Ey=Ty("iterator"),xy=Array.prototype;yd.exports=function(i){return i!==void 0&&(Iy.Array===i||xy[Ey]===i)}});var Ln=b((ok,Ed)=>{"use strict";var Py=hr(),Id=Nr(),wy=or(),ky=Ot(),Ay=de(),Ry=Ay("iterator");Ed.exports=function(i){if(!wy(i))return Id(i,Ry)||Id(i,"@@iterator")||ky[Py(i)]}});var Pd=b((uk,xd)=>{"use strict";var Ly=Se(),$y=it(),Cy=Fe(),Dy=_r(),My=Ln(),Oy=TypeError;xd.exports=function(i,e){var t=arguments.length<2?My(i):e;if($y(t))return Cy(Ly(t,i));throw Oy(Dy(i)+" is not iterable")}});var Ad=b((lk,kd)=>{"use strict";var By=Se(),wd=Fe(),Vy=Nr();kd.exports=function(i,e,t){var r,a;wd(i);try{if(r=Vy(i,"return"),!r){if(e==="throw")throw t;return t}r=By(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return wd(r),t}});var $a=b((ck,Cd)=>{"use strict";var _y=jr(),Ny=Se(),Fy=Fe(),qy=_r(),Uy=Td(),Hy=Ta(),Rd=Br(),jy=Pd(),Gy=Ln(),Ld=Ad(),Yy=TypeError,La=function(i,e){this.stopped=i,this.result=e},$d=La.prototype;Cd.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=_y(e,r),u,c,d,p,m,f,g,S=function(v){return u&&Ld(u,"normal",v),new La(!0,v)},y=function(v){return a?(Fy(v),o?l(v[0],v[1],S):l(v[0],v[1])):o?l(v,S):l(v)};if(s)u=i.iterator;else if(n)u=i;else{if(c=Gy(i),!c)throw Yy(qy(i)+" is not iterable");if(Uy(c)){for(d=0,p=Hy(i);p>d;d++)if(m=y(i[d]),m&&Rd($d,m))return m;return new La(!1)}u=jy(i,c)}for(f=s?i.next:u.next;!(g=Ny(f,u)).done;){try{m=y(g.value)}catch(v){Ld(u,"throw",v)}if(typeof m=="object"&&m&&Rd($d,m))return m}return new La(!1)}});var Md=b((dk,Dd)=>{"use strict";var Wy=ha(),Qy=Bt(),zy=qr();Dd.exports=function(i,e,t){var r=Wy(e);r in i?Qy.f(i,r,zy(0,t)):i[r]=t}});var Od=b(()=>{"use strict";var Ky=$e(),Jy=$a(),Xy=Md();Ky({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Jy(e,function(r,a){Xy(t,r,a)},{AS_ENTRIES:!0}),t}})});var Vd=b((fk,Bd)=>{"use strict";Rn();Od();var Zy=ca();Bd.exports=Zy.Object.fromEntries});var Nd=b((mk,_d)=>{"use strict";_d.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 Ud=b(()=>{"use strict";Rn();var eT=Nd(),tT=ue(),rT=hr(),iT=Vt(),Fd=Ot(),aT=de(),qd=aT("toStringTag");for(Ca in eT)$n=tT[Ca],Da=$n&&$n.prototype,Da&&rT(Da)!==qd&&iT(Da,qd,Ca),Fd[Ca]=Fd.Array;var $n,Da,Ca});var jd=b((vk,Hd)=>{"use strict";var sT=Vd();Ud();Hd.exports=sT});var Ma=b((Sk,Gd)=>{"use strict";var nT=jd();Gd.exports=nT});var Yd=b(()=>{"use strict"});var Wr=b((Ik,Wd)=>{"use strict";var oT=nr();Wd.exports=typeof process!="undefined"&&oT(process)=="process"});var zd=b((Ek,Qd)=>{"use strict";var uT=Bt();Qd.exports=function(i,e,t){return uT.f(i,e,t)}});var Xd=b((xk,Jd)=>{"use strict";var lT=rt(),cT=zd(),dT=de(),pT=ze(),Kd=dT("species");Jd.exports=function(i){var e=lT(i);pT&&e&&!e[Kd]&&cT(e,Kd,{configurable:!0,get:function(){return this}})}});var ep=b((Pk,Zd)=>{"use strict";var hT=Br(),fT=TypeError;Zd.exports=function(i,e){if(hT(e,i))return i;throw fT("Incorrect invocation")}});var Dn=b((wk,tp)=>{"use strict";var mT=ve(),bT=te(),Cn=pa(),gT=mT(Function.toString);bT(Cn.inspectSource)||(Cn.inspectSource=function(i){return gT(i)});tp.exports=Cn.inspectSource});var op=b((kk,np)=>{"use strict";var vT=ve(),ST=we(),rp=te(),yT=hr(),TT=rt(),IT=Dn(),ip=function(){},ET=[],ap=TT("Reflect","construct"),Mn=/^\s*(?:class|function)\b/,xT=vT(Mn.exec),PT=!Mn.exec(ip),Qr=function(e){if(!rp(e))return!1;try{return ap(ip,ET,e),!0}catch(t){return!1}},sp=function(e){if(!rp(e))return!1;switch(yT(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return PT||!!xT(Mn,IT(e))}catch(t){return!0}};sp.sham=!0;np.exports=!ap||ST(function(){var i;return Qr(Qr.call)||!Qr(Object)||!Qr(function(){i=!0})||i})?sp:Qr});var lp=b((Ak,up)=>{"use strict";var wT=op(),kT=_r(),AT=TypeError;up.exports=function(i){if(wT(i))return i;throw AT(kT(i)+" is not a constructor")}});var On=b((Rk,dp)=>{"use strict";var cp=Fe(),RT=lp(),LT=or(),$T=de(),CT=$T("species");dp.exports=function(i,e){var t=cp(i).constructor,r;return t===void 0||LT(r=cp(t)[CT])?e:RT(r)}});var hp=b((Lk,pp)=>{"use strict";var DT=ve();pp.exports=DT([].slice)});var mp=b(($k,fp)=>{"use strict";var MT=TypeError;fp.exports=function(i,e){if(i<e)throw MT("Not enough arguments");return i}});var Bn=b((Ck,bp)=>{"use strict";var OT=Vr();bp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(OT)});var Gn=b((Dk,Pp)=>{"use strict";var ke=ue(),BT=on(),VT=jr(),gp=te(),_T=He(),xp=we(),vp=mn(),NT=hp(),Sp=ua(),FT=mp(),qT=Bn(),UT=Wr(),Un=ke.setImmediate,Hn=ke.clearImmediate,HT=ke.process,Vn=ke.Dispatch,jT=ke.Function,yp=ke.MessageChannel,GT=ke.String,_n=0,zr={},Tp="onreadystatechange",Kr,Nt,Nn,Fn;xp(function(){Kr=ke.location});var jn=function(i){if(_T(zr,i)){var e=zr[i];delete zr[i],e()}},qn=function(i){return function(){jn(i)}},Ip=function(i){jn(i.data)},Ep=function(i){ke.postMessage(GT(i),Kr.protocol+"//"+Kr.host)};(!Un||!Hn)&&(Un=function(e){FT(arguments.length,1);var t=gp(e)?e:jT(e),r=NT(arguments,1);return zr[++_n]=function(){BT(t,void 0,r)},Nt(_n),_n},Hn=function(e){delete zr[e]},UT?Nt=function(i){HT.nextTick(qn(i))}:Vn&&Vn.now?Nt=function(i){Vn.now(qn(i))}:yp&&!qT?(Nn=new yp,Fn=Nn.port2,Nn.port1.onmessage=Ip,Nt=VT(Fn.postMessage,Fn)):ke.addEventListener&&gp(ke.postMessage)&&!ke.importScripts&&Kr&&Kr.protocol!=="file:"&&!xp(Ep)?(Nt=Ep,ke.addEventListener("message",Ip,!1)):Tp in Sp("script")?Nt=function(i){vp.appendChild(Sp("script"))[Tp]=function(){vp.removeChild(this),jn(i)}}:Nt=function(i){setTimeout(qn(i),0)});Pp.exports={set:Un,clear:Hn}});var Yn=b((Mk,kp)=>{"use strict";var wp=function(){this.head=null,this.tail=null};wp.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}}};kp.exports=wp});var Rp=b((Ok,Ap)=>{"use strict";var YT=Vr();Ap.exports=/ipad|iphone|ipod/i.test(YT)&&typeof Pebble!="undefined"});var $p=b((Bk,Lp)=>{"use strict";var WT=Vr();Lp.exports=/web0s(?!.*chrome)/i.test(WT)});var Np=b((Vk,_p)=>{"use strict";var Ft=ue(),Cp=jr(),QT=ln().f,Wn=Gn().set,zT=Yn(),KT=Bn(),JT=Rp(),XT=$p(),Qn=Wr(),Dp=Ft.MutationObserver||Ft.WebKitMutationObserver,Mp=Ft.document,Op=Ft.process,Oa=Ft.Promise,Bp=QT(Ft,"queueMicrotask"),Jn=Bp&&Bp.value,fr,zn,Kn,Ba,Vp;Jn||(Jr=new zT,Xr=function(){var i,e;for(Qn&&(i=Op.domain)&&i.exit();e=Jr.get();)try{e()}catch(t){throw Jr.head&&fr(),t}i&&i.enter()},!KT&&!Qn&&!XT&&Dp&&Mp?(zn=!0,Kn=Mp.createTextNode(""),new Dp(Xr).observe(Kn,{characterData:!0}),fr=function(){Kn.data=zn=!zn}):!JT&&Oa&&Oa.resolve?(Ba=Oa.resolve(void 0),Ba.constructor=Oa,Vp=Cp(Ba.then,Ba),fr=function(){Vp(Xr)}):Qn?fr=function(){Op.nextTick(Xr)}:(Wn=Cp(Wn,Ft),fr=function(){Wn(Xr)}),Jn=function(i){Jr.head||fr(),Jr.add(i)});var Jr,Xr;_p.exports=Jn});var qp=b((_k,Fp)=>{"use strict";Fp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Va=b((Nk,Up)=>{"use strict";Up.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var qt=b((Fk,Hp)=>{"use strict";var ZT=ue();Hp.exports=ZT.Promise});var Xn=b((qk,jp)=>{"use strict";jp.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Yp=b((Uk,Gp)=>{"use strict";var eI=Xn(),tI=Wr();Gp.exports=!eI&&!tI&&typeof window=="object"&&typeof document=="object"});var mr=b((Hk,zp)=>{"use strict";var rI=ue(),Zr=qt(),iI=te(),aI=cn(),sI=Dn(),nI=de(),oI=Yp(),uI=Xn(),lI=Ue(),Zn=Us(),Wp=Zr&&Zr.prototype,cI=nI("species"),eo=!1,Qp=iI(rI.PromiseRejectionEvent),dI=aI("Promise",function(){var i=sI(Zr),e=i!==String(Zr);if(!e&&Zn===66||lI&&!(Wp.catch&&Wp.finally))return!0;if(!Zn||Zn<51||!/native code/.test(i)){var t=new Zr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[cI]=r,eo=t.then(function(){})instanceof r,!eo)return!0}return!e&&(oI||uI)&&!Qp});zp.exports={CONSTRUCTOR:dI,REJECTION_EVENT:Qp,SUBCLASSING:eo}});var br=b((jk,Jp)=>{"use strict";var Kp=it(),pI=TypeError,hI=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw pI("Bad Promise constructor");e=r,t=a}),this.resolve=Kp(e),this.reject=Kp(t)};Jp.exports.f=function(i){return new hI(i)}});var bh=b(()=>{"use strict";var fI=$e(),mI=Ue(),qa=Wr(),It=ue(),yr=Se(),Xp=pr(),Zp=wn(),bI=wa(),gI=Xd(),vI=it(),Fa=te(),SI=Qe(),yI=ep(),TI=On(),ah=Gn().set,so=Np(),II=qp(),EI=Va(),xI=Yn(),sh=nn(),Ua=qt(),no=mr(),nh=br(),Ha="Promise",oh=no.CONSTRUCTOR,PI=no.REJECTION_EVENT,wI=no.SUBCLASSING,to=sh.getterFor(Ha),kI=sh.set,gr=Ua&&Ua.prototype,Ut=Ua,_a=gr,uh=It.TypeError,ro=It.document,oo=It.process,io=nh.f,AI=io,RI=!!(ro&&ro.createEvent&&It.dispatchEvent),lh="unhandledrejection",LI="rejectionhandled",eh=0,ch=1,$I=2,uo=1,dh=2,Na,th,CI,rh,ph=function(i){var e;return SI(i)&&Fa(e=i.then)?e:!1},hh=function(i,e){var t=e.value,r=e.state==ch,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===dh&&MI(e),e.rejection=uo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(uh("Promise-chain cycle")):(u=ph(l))?yr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},fh=function(i,e){i.notified||(i.notified=!0,so(function(){for(var t=i.reactions,r;r=t.get();)hh(r,i);i.notified=!1,e&&!i.rejection&&DI(i)}))},mh=function(i,e,t){var r,a;RI?(r=ro.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),It.dispatchEvent(r)):r={promise:e,reason:t},!PI&&(a=It["on"+i])?a(r):i===lh&&II("Unhandled promise rejection",t)},DI=function(i){yr(ah,It,function(){var e=i.facade,t=i.value,r=ih(i),a;if(r&&(a=EI(function(){qa?oo.emit("unhandledRejection",t,e):mh(lh,e,t)}),i.rejection=qa||ih(i)?dh:uo,a.error))throw a.value})},ih=function(i){return i.rejection!==uo&&!i.parent},MI=function(i){yr(ah,It,function(){var e=i.facade;qa?oo.emit("rejectionHandled",e):mh(LI,e,i.value)})},vr=function(i,e,t){return function(r){i(e,r,t)}},Sr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=$I,fh(i,!0))},ao=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw uh("Promise can't be resolved itself");var r=ph(e);r?so(function(){var a={done:!1};try{yr(r,e,vr(ao,a,i),vr(Sr,a,i))}catch(s){Sr(a,s,i)}}):(i.value=e,i.state=ch,fh(i,!1))}catch(a){Sr({done:!1},a,i)}}};if(oh&&(Ut=function(e){yI(this,_a),vI(e),yr(Na,this);var t=to(this);try{e(vr(ao,t),vr(Sr,t))}catch(r){Sr(t,r)}},_a=Ut.prototype,Na=function(e){kI(this,{type:Ha,done:!1,notified:!1,parent:!1,reactions:new xI,rejection:!1,state:eh,value:void 0})},Na.prototype=Xp(_a,"then",function(e,t){var r=to(this),a=io(TI(this,Ut));return r.parent=!0,a.ok=Fa(e)?e:!0,a.fail=Fa(t)&&t,a.domain=qa?oo.domain:void 0,r.state==eh?r.reactions.add(a):so(function(){hh(a,r)}),a.promise}),th=function(){var i=new Na,e=to(i);this.promise=i,this.resolve=vr(ao,e),this.reject=vr(Sr,e)},nh.f=io=function(i){return i===Ut||i===CI?new th(i):AI(i)},!mI&&Fa(Ua)&&gr!==Object.prototype)){rh=gr.then,wI||Xp(gr,"then",function(e,t){var r=this;return new Ut(function(a,s){yr(rh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete gr.constructor}catch(i){}Zp&&Zp(gr,_a)}fI({global:!0,constructor:!0,wrap:!0,forced:oh},{Promise:Ut});bI(Ut,Ha,!1,!0);gI(Ha)});var Th=b((Wk,yh)=>{"use strict";var OI=de(),vh=OI("iterator"),Sh=!1;try{gh=0,lo={next:function(){return{done:!!gh++}},return:function(){Sh=!0}},lo[vh]=function(){return this},Array.from(lo,function(){throw 2})}catch(i){}var gh,lo;yh.exports=function(i,e){if(!e&&!Sh)return!1;var t=!1;try{var r={};r[vh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var co=b((Qk,Ih)=>{"use strict";var BI=qt(),VI=Th(),_I=mr().CONSTRUCTOR;Ih.exports=_I||!VI(function(i){BI.all(i).then(void 0,function(){})})});var Eh=b(()=>{"use strict";var NI=$e(),FI=Se(),qI=it(),UI=br(),HI=Va(),jI=$a(),GI=co();NI({target:"Promise",stat:!0,forced:GI},{all:function(e){var t=this,r=UI.f(t),a=r.resolve,s=r.reject,n=HI(function(){var o=qI(t.resolve),l=[],u=0,c=1;jI(e,function(d){var p=u++,m=!1;c++,FI(o,t,d).then(function(f){m||(m=!0,l[p]=f,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var Ph=b(()=>{"use strict";var YI=$e(),WI=Ue(),QI=mr().CONSTRUCTOR,ho=qt(),zI=rt(),KI=te(),JI=pr(),xh=ho&&ho.prototype;YI({target:"Promise",proto:!0,forced:QI,real:!0},{catch:function(i){return this.then(void 0,i)}});!WI&&KI(ho)&&(po=zI("Promise").prototype.catch,xh.catch!==po&&JI(xh,"catch",po,{unsafe:!0}));var po});var wh=b(()=>{"use strict";var XI=$e(),ZI=Se(),eE=it(),tE=br(),rE=Va(),iE=$a(),aE=co();XI({target:"Promise",stat:!0,forced:aE},{race:function(e){var t=this,r=tE.f(t),a=r.reject,s=rE(function(){var n=eE(t.resolve);iE(e,function(o){ZI(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var kh=b(()=>{"use strict";var sE=$e(),nE=Se(),oE=br(),uE=mr().CONSTRUCTOR;sE({target:"Promise",stat:!0,forced:uE},{reject:function(e){var t=oE.f(this);return nE(t.reject,void 0,e),t.promise}})});var fo=b((iA,Ah)=>{"use strict";var lE=Fe(),cE=Qe(),dE=br();Ah.exports=function(i,e){if(lE(i),cE(e)&&e.constructor===i)return e;var t=dE.f(i),r=t.resolve;return r(e),t.promise}});var $h=b(()=>{"use strict";var pE=$e(),hE=rt(),Rh=Ue(),fE=qt(),Lh=mr().CONSTRUCTOR,mE=fo(),bE=hE("Promise"),gE=Rh&&!Lh;pE({target:"Promise",stat:!0,forced:Rh||Lh},{resolve:function(e){return mE(gE&&this===bE?fE:this,e)}})});var Ch=b(()=>{"use strict";bh();Eh();Ph();wh();kh();$h()});var Bh=b(()=>{"use strict";var vE=$e(),SE=Ue(),ja=qt(),yE=we(),Mh=rt(),Oh=te(),TE=On(),Dh=fo(),IE=pr(),bo=ja&&ja.prototype,EE=!!ja&&yE(function(){bo.finally.call({then:function(){}},function(){})});vE({target:"Promise",proto:!0,real:!0,forced:EE},{finally:function(i){var e=TE(this,Mh("Promise")),t=Oh(i);return this.then(t?function(r){return Dh(e,i()).then(function(){return r})}:i,t?function(r){return Dh(e,i()).then(function(){throw r})}:i)}});!SE&&Oh(ja)&&(mo=Mh("Promise").prototype.finally,bo.finally!==mo&&IE(bo,"finally",mo,{unsafe:!0}));var mo});var Ga=b((cA,Vh)=>{"use strict";var xE=rt();Vh.exports=xE});var Nh=b((dA,_h)=>{"use strict";Yd();Ch();Bh();var PE=Ga();_h.exports=PE("Promise","finally")});var qh=b((pA,Fh)=>{"use strict";var wE=Nh();Fh.exports=wE});var Ya=b((hA,Uh)=>{"use strict";var kE=qh();Uh.exports=kE});var Jh=b(()=>{"use strict";var ME=$e(),OE=Fr(),BE=Ta(),VE=ya(),_E=Ds();ME({target:"Array",proto:!0},{at:function(e){var t=OE(this),r=BE(t),a=VE(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});_E("at")});var Zh=b((fR,Xh)=>{"use strict";Jh();var NE=Ga();Xh.exports=NE("Array","at")});var tf=b((mR,ef)=>{"use strict";var FE=Zh();ef.exports=FE});var Qa=b((bR,rf)=>{"use strict";var qE=tf();rf.exports=qE});var xf=b(()=>{"use strict"});var Pf=b(()=>{"use strict"});var kf=b((YC,wf)=>{"use strict";var gx=Qe(),vx=nr(),Sx=de(),yx=Sx("match");wf.exports=function(i){var e;return gx(i)&&((e=i[yx])!==void 0?!!e:vx(i)=="RegExp")}});var Rf=b((WC,Af)=>{"use strict";var Tx=hr(),Ix=String;Af.exports=function(i){if(Tx(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Ix(i)}});var $f=b((QC,Lf)=>{"use strict";var Ex=Fe();Lf.exports=function(){var i=Ex(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 Mf=b((zC,Df)=>{"use strict";var xx=Se(),Px=He(),wx=Br(),kx=$f(),Cf=RegExp.prototype;Df.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Cf)&&!Px(i,"flags")&&wx(Cf,i)?xx(kx,i):e}});var Bf=b((KC,Of)=>{"use strict";var Bo=ve(),Ax=Fr(),Rx=Math.floor,Mo=Bo("".charAt),Lx=Bo("".replace),Oo=Bo("".slice),$x=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Cx=/\$([$&'`]|\d{1,2})/g;Of.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=Cx;return a!==void 0&&(a=Ax(a),l=$x),Lx(s,l,function(u,c){var d;switch(Mo(c,0)){case"$":return"$";case"&":return i;case"`":return Oo(e,0,t);case"'":return Oo(e,n);case"<":d=a[Oo(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var m=Rx(p/10);return m===0?u:m<=o?r[m-1]===void 0?Mo(c,1):r[m-1]+Mo(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var qf=b(()=>{"use strict";var Dx=$e(),Mx=Se(),Vo=ve(),Vf=na(),Ox=te(),Bx=or(),Vx=kf(),Pr=Rf(),_x=Nr(),Nx=Mf(),Fx=Bf(),qx=de(),Ux=Ue(),Hx=qx("replace"),jx=TypeError,Ff=Vo("".indexOf),Gx=Vo("".replace),_f=Vo("".slice),Yx=Math.max,Nf=function(i,e,t){return t>i.length?-1:e===""?t:Ff(i,e,t)};Dx({target:"String",proto:!0},{replaceAll:function(e,t){var r=Vf(this),a,s,n,o,l,u,c,d,p,m=0,f=0,g="";if(!Bx(e)){if(a=Vx(e),a&&(s=Pr(Vf(Nx(e))),!~Ff(s,"g")))throw jx("`.replaceAll` does not allow non-global regexes");if(n=_x(e,Hx),n)return Mx(n,e,r,t);if(Ux&&a)return Gx(Pr(r),e,t)}for(o=Pr(r),l=Pr(e),u=Ox(t),u||(t=Pr(t)),c=l.length,d=Yx(1,c),m=Nf(o,l,0);m!==-1;)p=u?Pr(t(l,m,o)):Fx(l,o,m,[],void 0,t),g+=_f(o,f,m)+p,f=m+c,m=Nf(o,l,m+d);return f<o.length&&(g+=_f(o,f)),g}})});var Hf=b((ZC,Uf)=>{"use strict";xf();Pf();qf();var Wx=Ga();Uf.exports=Wx("String","replaceAll")});var Gf=b((eD,jf)=>{"use strict";var Qx=Hf();jf.exports=Qx});var Wf=b((tD,Yf)=>{"use strict";var zx=Gf();Yf.exports=zx});var gP={};hb(gP,{ChromecastState:()=>Mr,HttpConnectionType:()=>ia,Observable:()=>et.Observable,PlaybackState:()=>ge,Player:()=>Wi,SDK_VERSION:()=>bP,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>aa,VERSION:()=>Ls,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>Tt,VideoQuality:()=>et.VideoQuality});module.exports=fb(gP);var Ls="__VERSION__";var ge=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ge||{}),Tt=(v=>(v.MPEG="MPEG",v.DASH="DASH_SEP",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Tt||{});var Mr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Mr||{}),ia=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ia||{});var aa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(aa||{});var V=require("@vkontakte/videoplayer-shared");var mu=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 sa=class{constructor(e){this.connection$=new V.ValueSubject(void 0);this.castState$=new V.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new V.Subject;this.realCastState$=new V.ValueSubject("NOT_AVAILABLE");this.subscription=new V.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,V.isNonNullable)((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||mu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:V.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,V.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,V.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,V.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,V.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,V.assertNever)(a.sessionState)}})).add((0,V.merge)((0,V.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,V.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,V.map)(a=>a.castState)),(0,V.observableFrom)([r.getCastState()])).pipe((0,V.filterChanged)(),(0,V.map)(mb),(0,V.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=(0,V.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,V.assertNonNullable)(l);let u=l.getCastDevice(),c=(o=l.getMediaSession())==null?void 0:o.media.contentId;((0,V.isNullable)(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"?(0,V.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:V.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},mb=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,V.assertNever)(i)}};var Bm=Ne(Ma(),1);var Yh=Ne(Ya(),1);var go=require("@vkontakte/videoplayer-shared");var pe=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,go.assertNever)(t)}return i},vo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,go.assertNever)(e)}};var P=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var Ke=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new Ke.Subject;this.transitionEnded$=new Ke.Subject;this.transitionUpdated$=new Ke.Subject;this.forceChanged$=new Ke.Subject;this.stateChangeStarted$=(0,Ke.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ke.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,Ke.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Hh=require("@vkontakte/videoplayer-shared"),jh=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Hh.assertNever)(i)}};var L=require("@vkontakte/videoplayer-shared");var AE=5,RE=5,LE=500,Gh=7e3,ei=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new L.Subject;e.add(a.pipe((0,L.debounce)(LE)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>AE)&&a.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),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<RE&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(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"),P(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"&&P(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];(0,L.assertNonNullable)(c);let d=(0,L.getHighestQuality)(Object.keys(c));(0,L.assertNonNullable)(d);let p=c[d];(0,L.assertNonNullable)(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=pe(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((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(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(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((0,L.timeout)(Gh).subscribe(()=>s(`timeout(${Gh})`)))});(0,Yh.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ti=i=>{i.removeAttribute("src"),i.load()};var Wh=i=>{try{i.pause(),i.playbackRate=0,ti(i),i.remove()}catch(e){console.error(e)}};var So=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)}},yo=window.WeakMap?new WeakMap:new So,ye=i=>{let e=i.querySelector("video"),t=!!e;return e?ti(e):(e=document.createElement("video"),i.appendChild(e)),yo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Te=i=>{let e=yo.get(i);yo.delete(i),e?ti(i):Wh(i)};var $=require("@vkontakte/videoplayer-shared");var Et=require("@vkontakte/videoplayer-shared"),Wa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,Et.isNullable)(a),u=new Et.Subscription;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},Je=(i,e,t)=>Wa(e,()=>i.loop,r=>{(0,Et.isNonNullable)(r)&&(i.loop=r)},{onError:t}),Ie=(i,e,t,r)=>Wa(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,Et.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ce=(i,e,t,r)=>Wa(e,()=>i.playbackRate,a=>{(0,Et.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),xt=Wa;var $E=i=>["__",i.language,i.label].join("|"),CE=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},To=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(xt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(xt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(xt(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(xt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var u,c,d,p,m;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),(m=o.target)==null||m.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;(0,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,l;let{language:t,label:r}=e,a=e.id?e.id:$E(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){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!CE(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,$.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,$.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},De=To;var nt=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 Qh=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},Io=i=>{let e=Qh(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},zh=i=>{let e=Qh(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var R=require("@vkontakte/videoplayer-shared");var DE=3,Kh=(i,e,t=DE)=>{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 Ee=i=>{let e=w=>(0,R.fromEvent)(i,w).pipe((0,R.mapTo)(void 0)),r=(0,R.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>(0,R.fromEvent)(i,w))).pipe((0,R.map)(w=>w.type==="ended"?i.readyState<2:i.readyState<3),(0,R.filterChanged)()),a=(0,R.merge)((0,R.fromEvent)(i,"progress"),(0,R.fromEvent)(i,"timeupdate")).pipe((0,R.map)(()=>Kh(i.buffered,i.currentTime))),n=(0,R.getCurrentBrowser)().browser===R.CurrentClientBrowser.Safari?(0,R.combine)({play:e("play").pipe((0,R.once)()),playing:e("playing")}).pipe((0,R.mapTo)(void 0)):e("playing"),o=(0,R.fromEvent)(i,"volumechange").pipe((0,R.map)(()=>({muted:i.muted,volume:i.volume}))),l=(0,R.fromEvent)(i,"ratechange").pipe((0,R.map)(()=>i.playbackRate)),u=(0,R.fromEvent)(i,"error").pipe((0,R.filter)(()=>!!(i.error||i.played.length)),(0,R.map)(()=>{var E;let w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:R.ErrorCategory.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(E=i.error)!=null?E:void 0}})),c=(0,R.fromEvent)(i,"timeupdate").pipe((0,R.map)(()=>i.currentTime)),d=new R.Subject,p=.3,m;c.subscribe(w=>{i.loop&&(0,R.isNonNullable)(m)&&(0,R.isNonNullable)(w)&&m>=i.duration-p&&w<=p&&d.next(m),m=w});let f=(0,R.fromEvent)(i,"enterpictureinpicture"),g=(0,R.fromEvent)(i,"leavepictureinpicture"),S=new R.ValueSubject(zh(i));f.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let y=new R.ValueSubject(Io(i));return(0,R.fromEvent)(i,"fullscreenchange").pipe((0,R.map)(()=>Io(i))).subscribe(y),{playing$:n,pause$:e("pause").pipe((0,R.filter)(()=>!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$:(0,R.fromEvent)(i,"durationchange").pipe((0,R.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:S,inFullscreen$:y}};var ot=require("@vkontakte/videoplayer-shared"),Pt=i=>{switch(i){case"mobile":return ot.VideoQuality.Q_144P;case"lowest":return ot.VideoQuality.Q_240P;case"low":return ot.VideoQuality.Q_360P;case"sd":case"medium":return ot.VideoQuality.Q_480P;case"hd":case"high":return ot.VideoQuality.Q_720P;case"fullhd":case"full":return ot.VideoQuality.Q_1080P;case"quadhd":case"quad":return ot.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ot.VideoQuality.Q_2160P}};var xo=Ne(Qa(),1),F=require("@vkontakte/videoplayer-shared");var Eo=!1,ut={},af=i=>{Eo=i},sf=()=>{ut={}},nf=i=>{i(ut)},ri=(i,e)=>{var t;Eo&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[i]=e)},fe=class{constructor(e){this.name=e}next(e){var r,a;if(!Eo)return;ut.series=(r=ut.series)!=null?r:{};let t=(a=ut.series[this.name])!=null?a:[];t.push([Date.now(),e]),ut.series[this.name]=t}};var UE=new fe("best_bitrate"),HE=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,za=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,F.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jE='Assertion "ABR Tracks is empty array" failed',GE=(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 j,G,M,ie,me;(0,F.assertNotEmptyArray)(i,jE);let p=r.usePixelRatio&&(j=window.devicePixelRatio)!=null?j:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=m&&(0,F.videoSizeToQuality)(m),g=r.considerPlaybackRate&&(0,F.isNonNullable)(o)?o:1,S=i.filter(B=>!(0,F.isInvariantQuality)(B.quality)).sort((B,A)=>(0,F.isHigher)(B.quality,A.quality)?-1:1),y=(G=(0,xo.default)(S,-1))==null?void 0:G.quality,v=(M=(0,xo.default)(S,0))==null?void 0:M.quality,w=(0,F.isNullable)(a)||(0,F.isNonNullable)(a.min)&&(0,F.isNonNullable)(a.max)&&(0,F.isLower)(a.max,a.min)||(0,F.isNonNullable)(a.min)&&v&&(0,F.isHigher)(a.min,v)||(0,F.isNonNullable)(a.max)&&y&&(0,F.isLower)(a.max,y),E=g*HE(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),k={},U=S.filter(B=>(f?(0,F.isLower)(B.quality,f):!0)?((0,F.isNonNullable)(t)&&isFinite(t)&&(0,F.isNonNullable)(B.bitrate)?t-s>=B.bitrate*E:!0)?r.lazyQualitySwitch&&(0,F.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,F.isInvariantQuality)(l.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,F.isHigher)(B.quality,l.quality)?(k[B.quality]="Buffer",!1):!!c&&(0,F.isHigherOrEqual)(B.quality,c)?(k[B.quality]="DroppedFramesLimit",!1):w||((0,F.isNullable)(a.max)||(0,F.isLowerOrEqual)(B.quality,a.max))&&((0,F.isNullable)(a.min)||(0,F.isHigherOrEqual)(B.quality,a.min))?!0:(k[B.quality]="FitsQualityLimits",!1):(k[B.quality]="FitsThroughput",!1):(k[B.quality]="FitsContainer",!1))[0];U&&U.bitrate&&UE.next(U.bitrate);let _=(ie=U!=null?U:S[Math.ceil((S.length-1)/2)])!=null?ie:i[0];_.quality!==((me=u==null?void 0:u.last)==null?void 0:me.quality)&&d({message:`
7
7
  [available tracks]
8
- ${i.map(L=>`{ id: ${L.id}, quality: ${L.quality}, bitrate: ${L.bitrate} }`).join(`
8
+ ${i.map(B=>`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(s!=null?s:{}).map(([L,A])=>`${L}: ${A}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([B,A])=>`${B}: ${A}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
- containerQualityLimit: ${T},
16
+ containerQualityLimit: ${f},
17
17
  throughput: ${t},
18
- reserve: ${n},
19
- playbackRate: ${l},
20
- playbackRateFactor: ${E},
21
- forwardBufferHealth: ${o},
22
- bitrateFactor: ${R},
23
- minBufferToSwitchUp: ${s.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${h},
25
- limitsAreInvalid: ${V},
18
+ reserve: ${s},
19
+ playbackRate: ${o},
20
+ playbackRateFactor: ${g},
21
+ forwardBufferHealth: ${n},
22
+ bitrateFactor: ${E},
23
+ minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
+ droppedVideoMaxQualityLimit: ${c},
25
+ limitsAreInvalid: ${w},
26
26
  maxQualityLimit: ${a==null?void 0:a.max},
27
27
  minQualityLimit: ${a==null?void 0:a.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(F).map(([L,A])=>`${L}: ${A}`).join(`
30
+ ${Object.entries(k).map(([B,A])=>`${B}: ${A}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${C==null?void 0:C.quality}
34
- [selected track] ${w==null?void 0:w.quality}
35
- `});const Y=w&&u&&u.history[w.id]&&r.now()-u.history[w.id]<=s.trackCooldown&&(!u.last||w.id!==u.last.id);if(w!=null&&w.id&&u&&!Y&&u.recordSelection(w),Y&&(u!=null&&u.last)){const L=u.last;return u==null||u.recordSwitch(L),d({message:`
36
- [last selected] ${L==null?void 0:L.quality}
37
- `}),L}return u==null||u.recordSwitch(w),w};var Le=i=>new URL(i).hostname,_;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(_||(_={}));const Cr=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 ct=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!Cr(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return Cr(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function re(){return r.now()}function zn(i){return re()-i}function Lr(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,a=o=>s.test(o);return{resolve:(o,l,c=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return c&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function Pf(i,e,t){const s=(...a)=>{t.apply(null,a),i.removeEventListener(e,s)};i.addEventListener(e,s)}function $i(i,e,t,s){const a=window.XMLHttpRequest;let n,o,l,c=!1,u=0,h,d,f=!1,p="arraybuffer",v=7e3,m=2e3,S=()=>{if(c)return;r.assertNonNullable(h);const C=zn(h);let w;if(C<m){w=m-C,setTimeout(S,w);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new a,N()};const b=C=>(n=C,j),y=C=>(d=C,j),T=()=>(p="json",j),E=()=>{if(!c){if(--u>=0){S(),s&&s();return}c=!0,d&&d(),t&&t()}},$=C=>(f=C,j),N=()=>{h=re(),o=new a,o.open("get",i);let C=0,w,Y=0;const L=()=>(r.assertNonNullable(h),Math.max(h,Math.max(w||0,Y||0)));if(n&&o.addEventListener("progress",A=>{const U=re();n.updateChunk&&A.loaded>C&&(n.updateChunk(L(),A.loaded-C),C=A.loaded,w=U)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(c)return;r.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const U=o.response.byteLength-C;U&&n.updateChunk&&n.updateChunk(L(),U)}o.responseType==="json"&&!Object.values(o.response).length?E():(d&&d(),e(o.response))}else E()}),o.addEventListener("error",()=>{E()}),f){const A=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=re(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=p,o.send(),j},j={withBitrateReporting:b,withParallel:$,withJSONResponse:T,withRetryCount:C=>(u=C,j),withRetryInterval:(C,w)=>(r.isNonNullable(C)&&(m=C),r.isNonNullable(w)&&(v=w),j),withTimeout:C=>(l=C,j),withFinally:y,send:N,abort:()=>{o&&(o.abort(),o=void 0),c=!0,d&&d()}};return j}const Cf=100,Lf=2e3,Df=500;let xf=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-Df;if(t-e>Lf){let s=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const c=n.bytes*o/l;a+=c,n.start=t,n.bytes-=c}}}if(a>0&&s>0){const n=a*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${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>Cf&&(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 _f{constructor(e,t,s,a,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=a,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=re(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=c=>{e._complete=1,e._responseData=c,e._downloadTime=re()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=$i(t,n,()=>a("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=re()}_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=re();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,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=a,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=a,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const fi=1e4,$s=3,Rf=6e4,If=10,Nf=1,Of=500;class Mf{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 xf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Lr(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=Lr(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 a;s!==0&&(a=t.buffered.start(s-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let s,a,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!a||n.bitrate>a.bitrate)&&(a=n):(!s||s.bitrate>n.bitrate)&&(s=n));return a||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("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())});const o=()=>{Pf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _f($s,fi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:a}=this.params;let n=!1,o=null,l=null,c=null,u=null,h=!1;const d=()=>{const E=n&&(!h||h===this.rep);return E||t("Not running!"),E},f=(E,$,N)=>{c&&c.abort(),c=$i(this.urlResolver.resolve(E,!1),$,N,()=>this._retryCallback()).withTimeout(fi).withBitrateReporting(this.bitrateSwitcher).withRetryCount($s).withFinally(()=>{c=null}).send()},p=(E,$,N)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,N,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=E=>{const $=s.playbackRate;s.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),s.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const N=re()-1e4;let O=0;for(let R=0;R<this.bufferStates.length;R++){const F=this.bufferStates[R];E=Math.min(E,F.buf),F.ts<N&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${E} drop=${O} jitter=${this.sourceJitter}`);let V=E-Nf;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?v(1.15):V>1?v(1.1):V>.3?v(1.05):v(1)}},b=E=>{let $;const N=()=>$&&$.start?$.start.length:0,O=A=>$.start[A]/1e3,V=A=>$.dur[A]/1e3,R=A=>$.fragIndex+A,F=(A,U)=>({chunkIdx:R(A),startTS:O(A),dur:V(A),discontinuity:U}),j=()=>{let A=0;if($&&$.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=U;this.sourceJitter>1&&(X+=this.sourceJitter-1);let te=$.dur.length-1;for(;te>=0&&(X-=$.dur[te],!(X<=0));--te);A=Math.min(te,$.dur.length-1-Q),A=Math.max(A,0)}return F(A,!0)},C=A=>{const U=N();if(!(U<=0)){if(r.isNonNullable(A)){for(let Q=0;Q<U;Q++)if(O(Q)>A)return F(Q)}return j()}},w=A=>{const U=N(),Q=A?A.chunkIdx+1:0,X=Q-$.fragIndex;if(!(U<=0)){if(!A||X<0||X-U>If)return t(`Resync: offset=${X} bChunks=${U} chunk=`+JSON.stringify(A)),j();if(!(X>=U))return F(Q-$.fragIndex,!1)}},Y=(A,U,Q)=>{u&&u.abort(),u=$i(this.urlResolver.resolve(A,!0,this.lowLatency),U,Q,()=>this._retryCallback()).withTimeout(fi).withRetryCount($s).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,U)=>{Y(E,Q=>{if(!d())return;$=Q;const X=!!$.lowLatency;X!==this.lowLatency&&m(X);let te=0;for(let Ee=0;Ee<$.dur.length;++Ee)te+=$.dur[Ee];te>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/$.dur.length)),a({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,A(C(U))},()=>this._handleNetworkError())},nextChunk:w}},y=()=>{n=!1,l&&l.abort(),c&&c.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:E=>{const{videoElement:$,logger:N}=this.params;let O=b(e.jidxUrl),V,R,F,j,C=0,w,Y,L;const A=()=>{w&&(clearTimeout(w),w=void 0);const B=Math.max(Of,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=C+B,oe=re(),le=Math.min(1e4,se-oe);C=oe;const ft=()=>{u||d()&&O.seek(()=>{d()&&(C=re(),U(),A())})};le>0?w=window.setTimeout(()=>{this.paused?A():ft()},le):ft()},U=()=>{let B;for(;B=O.nextChunk(j);)j=B,Nt(B);const se=O.nextChunk(F);if(se){if(F&&se.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?A():(y(),this._initPlayerWith(e));return}Ee(se)}else A()},Q=(B,se)=>{if(!d()||!this.sourceBuffer)return;let oe,le,ft;const Ot=De=>{window.setTimeout(()=>{d()&&Q(B,se)},De)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Ot(100);else{const De=re(),de=$.currentTime;!this.paused&&$.buffered.length>1&&Y===de&&De-L>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),Y!==de&&(Y=de,L=De);const pt=this._getBufferSizeSec();if(pt>30)N(`Buffered ${pt} seconds; delaying appendBuffer`),Ot(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:De,buf:pt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(Mt){if(Mt.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),ft=this.sourceBuffer.buffered.length,ft!==0&&(oe=this.sourceBuffer.buffered.start(0),le=de,le-oe>4&&this.sourceBuffer.remove(oe,le-3)),Ot(1e3);else throw Mt}}},X=()=>{R&&V&&(N([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(F)]),Q(R,function(){R=null,U()}))},te=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),Ee=B=>{d()&&p(te(B),(se,oe)=>{if(d()){if(oe/=1e3,R=se,F=B,o=B.startTS,oe){const le=Math.min(10,B.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*le:le}X()}},()=>this._handleNetworkError())},Nt=B=>{d()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(B),!1)))},ht=B=>{d()&&(e.cachedHeader=B,Q(B,()=>{V=!0,X()}))};n=!0,O.seek(B=>{if(d()){if(C=re(),!B){A();return}j=B,!r.isNullable(E)||B.startTS>E?Ee(B):(F=B,U())}},E),e.cachedHeader?ht(e.cachedHeader):f(e.headerUrl,ht,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},h}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=d=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),v=d/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},n=(()=>({updateChunk:(f,p)=>{const v=re();if(this.chunkRateEstimator.addInterval(f,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,c=!0;const u=()=>{let d=n.get();if(d&&l&&this.autoQuality){if(c&&d>l&&zn(o)<3e4)return;s(d)}c=this.autoQuality};return{updateChunk:(d,f)=>{const p=n.updateChunk(d,f);return p&&u(),p},notifySwitch:d=>{const f=re();d<l&&(o=f),l=d}}}_fetchManifest(e,t,s){this.manifestRequest=$i(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(fi).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;ct(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(_.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,l.push(c))}),l.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),l):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=n(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))},Rf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Wn{constructor(){this.onDroopedVideoFramesLimit$=new r.Subject,this.subscription=new r.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new r.Subject,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!r.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),a=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(a-n)/a;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&r.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),s=r.merge(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 a=(s=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>r.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:a}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 Ks=()=>{var i;return!!(!((i=window.documentPictureInPicture)===null||i===void 0)&&i.window)||!!document.pictureInPictureElement},It=(i,e)=>new r.Observable(t=>{if(!window.IntersectionObserver)return;const s={root:null},a=new IntersectionObserver((o,l)=>{o.forEach(c=>t.next(c.isIntersecting||Ks()))},{...s,...e});a.observe(i);const n=r.fromEvent(document,"visibilitychange").pipe(r.map(o=>!document.hidden||Ks())).subscribe(o=>t.next(o));return()=>{a.unobserve(i),n.unsubscribe}}),Bf=[_.PAUSED,_.PLAYING,_.READY],Vf=[_.PAUSED,_.PLAYING,_.READY];class Ff{constructor(e){this.subscription=new r.Subscription,this.videoState=new J(_.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new qe,this.droppedFramesManager=new Wn,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new va,this._dashCb=a=>{var n,o,l,c;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,h=[];for(const d of u){const f=(n=d.name)!==null&&n!==void 0?n:d.index.toString(10),p=(o=Fi(d.name))!==null&&o!==void 0?o:r.videoSizeToQuality(d.video),v=d.bitrate/1e3,m={...d.video};if(!p)continue;const S={id:f,quality:p,bitrate:v,size:m};h.push({track:S,representation:d})}this.representations$.next(h),this.params.output.availableVideoTracks$.next(h.map(({track:d})=>d)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===_.MANIFEST_READY&&this.videoState.setState(_.MANIFEST_READY);break}case"qualitySwitch":{const u=a.quality,h=(c=this.representations$.getValue().find(({representation:d})=>d===u))===null||c===void 0?void 0:c.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),r.isNonNullable(h)&&this.params.output.currentVideoTrack$.next(h);break}case"bandwidth":{const{size:u,duration:h}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,h);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration||0),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(c)};`}),o===exports.PlaybackState.STOPPED){a!==_.STOPPED&&(this.videoState.startTransitionTo(_.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(_.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Vf.includes(a)&&(u||h)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===I.Requested&&Bf.includes(a)){this.seek(c.position-this.liveOffset.getTotalPausedTime());return}switch(a){case _.STOPPED:this.videoState.startTransitionTo(_.MANIFEST_READY),this.dash.attachSource(ge(this.params.source.url));return;case _.MANIFEST_READY:this.videoState.startTransitionTo(_.READY),this.prepare();break;case _.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(_.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(_.PLAYING);const d=l==null?void 0:l.from;d&&d===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play()}return;case _.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(_.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case _.PAUSED:if(o===exports.PlaybackState.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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(ge(this.params.source.url,d))}return;default:return r.assertNever(a)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=ot(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(Le(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=dt(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.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===_.READY&&this.videoState.setState(_.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(_.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===I.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(_.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(Kt(this.video,this.params.desiredState.isLooped,t)).add(ut(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Rt(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(It(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{const n=a&&r.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case _.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case _.MANIFEST_READY:case _.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case _.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case _.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),lt(this.video)}createLiveDashPlayer(){const e=new Mf({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,a,n,o;const l=this.representations$.getValue(),c=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(a=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&r.isNonNullable(c)?c:Ui(l.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),d=h==null?void 0:h.id,f=this.params.desiredState.videoTrack.getTransition(),p=(n=this.params.desiredState.videoTrack.getState())===null||n===void 0?void 0:n.id,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(h&&(f||d!==p)&&this.setVideoTrack(h),v&&this.setAutoQuality(u),f||v||d!==p){const m=(o=l.find(({track:S})=>S.id===d))===null||o===void 0?void 0:o.representation;r.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:a})=>a.id===e.id))===null||t===void 0?void 0:t.representation;r.assertNonNullable(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(),a=t===exports.PlaybackState.PAUSED&&s===_.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ge(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var ie;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ie||(ie={}));var Ae;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(Ae||(Ae={}));var Ci;(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"})(Ci||(Ci={}));var pe;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(pe||(pe={}));var D;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(D||(D={}));var Lt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Lt||(Lt={}));var Li;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Li||(Li={}));var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));var jt=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const a=i.start(s)*1e3,n=i.end(s)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};class Dr{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 a=0,n=s.length;a<n;a++)if(s[a].callback===t){s.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let a=0,n=s.length;a<n;a++){const o=s[a];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Qn extends Dr{constructor(){super(),this.listeners||Dr.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 Kn=class{constructor(){Object.defineProperty(this,"signal",{value:new Qn,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 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(a){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&&(Kn.prototype[Symbol.toStringTag]="AbortController",Qn.prototype[Symbol.toStringTag]="AbortSignal");function Jn(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 Uf(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Jn({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,h){let d;h&&h.signal&&(d=h.signal,delete h.signal);const f=new t(u,h);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},n.prototype=t.prototype);const o=e;return{fetch:(c,u)=>{const h=n&&n.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(h){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(h.aborted)return Promise.reject(d);const f=new Promise((p,v)=>{h.addEventListener("abort",()=>v(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(c,u)])}return o(c,u)},Request:n}}const ji=Jn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Xn=ji?Uf({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Yt=ji?Xn.fetch:window.fetch;ji?Xn.Request:window.Request;const Ct=ji?Kn:window.AbortController;var Js=(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 jf=(i,e={})=>{const s=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Hf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",xr=Hf?jf:window.requestIdleCallback;var ks,As;const Gf=16;let Zn=!1;try{Zn=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt((As=(ks=navigator.userAgent.match(/Version\/(\d+)/))===null||ks===void 0?void 0:ks[1])!==null&&As!==void 0?As:"",10)<=Gf}catch(i){console.error(i)}class Yf{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,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:r.ErrorCategory.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 a={operation:"append",data:e,signal:t,callback:s};this.queue.push(a),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:s,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let s;Zn&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!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(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}var _r=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class ue{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 a=this.size32?this.size32-8:void 0,n=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,n,a),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 eo extends ue{}class qf extends ue{}class zf extends ue{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 a=this.readString(4);this.compatibleBrands.push(a),s-=4}}}class Wf extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Qf extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Kf extends ue{constructor(e,t){super(e,t),this.data=this.content}}class Fe extends ue{constructor(e,t){super(e,t);const s=this.readUint32();this.version=s>>>24,this.flags=s&16777215}}class to extends Fe{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 a=this.readUint32();const n=a>>>31,o=a<<1>>>1,l=this.readUint32();a=this.readUint32();const c=a>>>28,u=a<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:c,SAPDeltaTime:u})}}}class Jf extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Xf extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var it;(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"})(it||(it={}));class Zf extends Fe{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=it.MONOSCOPIC;break;case 1:this.stereoMode=it.TOP_BOTTOM;break;case 2:this.stereoMode=it.LEFT_RIGHT;break;case 3:this.stereoMode=it.STEREO_CUSTOM;break;case 4:this.stereoMode=it.RIGHT_LEFT;break}this.cursor+=1}}class ep extends Fe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class tp extends Fe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class ip extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class sp extends Fe{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 ap extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class rp extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class np extends Fe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class op extends ue{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class lp extends Fe{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 up extends Fe{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 dp extends Fe{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 z;(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"})(z||(z={}));const cp={[z.FtypBox]:zf,[z.MoovBox]:Wf,[z.MoofBox]:Qf,[z.MdatBox]:Kf,[z.SidxBox]:to,[z.TrakBox]:Jf,[z.MdiaBox]:ip,[z.MfhdBox]:np,[z.TkhdBox]:sp,[z.TrafBox]:op,[z.TfhdBox]:lp,[z.TfdtBox]:up,[z.TrunBox]:dp,[z.MinfBox]:ap,[z.Sv3dBox]:Xf,[z.St3dBox]:Zf,[z.PrhdBox]:ep,[z.ProjBox]:rp,[z.EquiBox]:tp,[z.UuidBox]:qf,[z.UnknownBox]:eo};class st{constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let s=this.options.offset;for(;s<e.byteLength;)try{const n=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+s+4,4)),o=this.createBox(n,new DataView(e.buffer,e.byteOffset+s));if(!o.size)break;t.push(o),s+=o.size}catch(a){break}return t}createBox(e,t){const s=cp[e];return s?new s(t,new st):new eo(t,new st)}}class ba{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var s,a,n;(s=(a=this.index)[n=t.type])!==null&&s!==void 0||(a[n]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const hp=new TextDecoder("ascii"),fp=i=>hp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",pp=i=>{const e=new to(i,new st);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:D.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},mp=(i,e)=>{const s=new st().parse(i),a=new ba(s),n=a.findAll("moof"),o=e?a.findAll("uuid"):a.findAll("mdat");if(!(o.length&&n.length))return null;const l=n[0],c=o[o.length-1],u=l.source.byteOffset,d=c.source.byteOffset-l.source.byteOffset+c.size;return new DataView(i.buffer,u,d)},vp=(i,e)=>{const s=new st().parse(i),n=new ba(s).findAll("traf"),o=n[n.length-1].children.find(d=>d.type==="tfhd"),l=n[n.length-1].children.find(d=>d.type==="tfdt"),c=n[n.length-1].children.find(d=>d.type==="trun");let u=0;return c.sampleDuration.length?u=c.sampleDuration.reduce((d,f)=>d+f,0):u=o.defaultSampleDuration*c.sampleCount,(Number(l.baseMediaDecodeTime)+u)/e*1e3},Sp=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},s=new st().parse(i),a=new ba(s);if(a.find("sv3d")){e.is3dVideo=!0;const o=a.find("st3d");o&&(e.stereoMode=o.stereoMode);const l=a.find("prhd");l&&(e.projectionData.pose.yaw=l.poseYawDegrees,e.projectionData.pose.pitch=l.posePitchDegrees,e.projectionData.pose.roll=l.poseRollDegrees);const c=a.find("equi");c&&(e.projectionData.bounds.top=c.projectionBoundsTop,e.projectionData.bounds.right=c.projectionBoundsRight,e.projectionData.bounds.bottom=c.projectionBoundsBottom,e.projectionData.bounds.left=c.projectionBoundsLeft)}return e},bp={validateData:fp,parseInit:Sp,getIndexRange:()=>{},parseSegments:pp,parseFeedableSegmentChunk:mp,getSegmentEndTime:vp};var g;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(g||(g={}));var k;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(k||(k={}));const Rr={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.TrackEntry]:{type:k.Master},[g.Video]:{type:k.Master},[g.Projection]:{type:k.Master},[g.ProjectionType]:{type:k.UnsignedInteger},[g.ProjectionPrivate]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},io=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=Di(i,t),a=s in Rr,n=a?Rr[s].type:k.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const c=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,h=Di(c),d=u*2**((l-1)*8)+h,f=t+l;let p;return f+d>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,d),{tag:a?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},Di=(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},Pe=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return Di(i);case k.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(i);case k.UTF8:return new TextDecoder("utf-8").decode(i);case k.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case k.Master:return i;case k.Binary:return i;default:r.assertNever(e)}},Dt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),a=io(s);if(!e(a))return;a.type===k.Master&&Dt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},gp=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,s;const a=io(i);return Dt(a.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Pe(l,o):n===g.DocType?t=Pe(l,o):n===g.DocTypeReadVersion&&(s=Pe(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},so=[g.Info,g.SeekHead,g.Tracks,g.TrackEntry,g.Video,g.Projection,g.ProjectionType,g.ProjectionPrivate,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],yp=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],Tp=i=>{let e,t,s,a,n=!1,o=!1,l=!1,c,u,h=!1;const d=0;return Dt(i,({tag:f,type:p,value:v,valueSize:m})=>{if(f===g.SeekID){const S=Pe(v,p);u=Di(S)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=v.byteOffset,t=v.byteOffset+m):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?s=Pe(v,p):f===g.Duration?a=Pe(v,p):f===g.SeekPosition&&u===g.Cues?c=Pe(v,p):f===g.Tracks?Dt(v,({tag:S,type:b,value:y})=>S===g.ProjectionType?(h=Pe(y,b)===1,!1):!0):n&&o&&so.includes(f)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"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(a/1e9*s*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:d,projectionType:Li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ep=i=>{if(r.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$p=(i,e)=>{let t=!1,s=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Dt(i,({tag:l,type:c,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&a(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Pe(u,c));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Pe(u,c));break;default:t&&so.includes(l)&&(s=!0)}return!(t&&s)}),o&&a(o)&&n.push(o),n.map((l,c)=>{const{time:u,position:h}=l,d=n[c+1];return{status:D.NONE,time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},kp=i=>{let e=0,t=!1;try{Dt(i,s=>s.tag===g.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):yp.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ap={validateData:gp,parseInit:Tp,getIndexRange:Ep,parseSegments:$p,parseFeedableSegmentChunk:kp};var wp=at,Pp=Ri,Cp=Te,Lp=Cp("match"),Dp=function(i){var e;return wp(i)&&((e=i[Lp])!==void 0?!!e:Pp(i)=="RegExp")},xp=Vi,_p=String,Rp=function(i){if(xp(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return _p(i)},Ip=nt,Np=function(){var i=Ip(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},Op=Be,Mp=Ve,Bp=ra,Vp=Np,Ir=RegExp.prototype,Fp=function(i){var e=i.flags;return e===void 0&&!("flags"in Ir)&&!Mp(i,"flags")&&Bp(Ir,i)?Op(Vp,i):e},ga=Me,Up=Oi,jp=Math.floor,ws=ga("".charAt),Hp=ga("".replace),Ps=ga("".slice),Gp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Yp=/\$([$&'`]|\d{1,2})/g,qp=function(i,e,t,s,a,n){var o=t+i.length,l=s.length,c=Yp;return a!==void 0&&(a=Up(a),c=Gp),Hp(n,c,function(u,h){var d;switch(ws(h,0)){case"$":return"$";case"&":return i;case"`":return Ps(e,0,t);case"'":return Ps(e,o);case"<":d=a[Ps(h,1,-1)];break;default:var f=+h;if(f===0)return u;if(f>l){var p=jp(f/10);return p===0?u:p<=l?s[p-1]===void 0?ws(h,1):s[p-1]+ws(h,1):u}d=s[f-1]}return d===void 0?"":d})},zp=Bi,Wp=Be,ya=Me,Nr=ia,Qp=me,Kp=Ii,Jp=Dp,Tt=Rp,Xp=Ni,Zp=Fp,em=qp,tm=Te,im=tm("replace"),sm=TypeError,ao=ya("".indexOf),am=ya("".replace),Or=ya("".slice),rm=Math.max,Mr=function(i,e,t){return t>i.length?-1:e===""?t:ao(i,e,t)};zp({target:"String",proto:!0},{replaceAll:function(e,t){var s=Nr(this),a,n,o,l,c,u,h,d,f,p=0,v=0,m="";if(!Kp(e)){if(a=Jp(e),a&&(n=Tt(Nr(Zp(e))),!~ao(n,"g")))throw sm("`.replaceAll` does not allow non-global regexes");if(o=Xp(e,im),o)return Wp(o,e,s,t);if(a)return am(Tt(s),e,t)}for(l=Tt(s),c=Tt(e),u=Qp(t),u||(t=Tt(t)),h=c.length,d=rm(1,h),p=Mr(l,c,0);p!==-1;)f=u?Tt(t(c,p,l)):em(c,l,p,[],void 0,t),m+=Or(l,v,p)+f,v=p+h,p=Mr(l,c,p+d);return v<l.length&&(m+=Or(l,v)),m}});var nm=qn,om=nm("String","replaceAll"),lm=om,um=lm,dm=um,cm=dm,Br=ta(cm);const hm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Vr=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const c=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(c)?0:c)*l},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),a=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],a),hours:e(s==null?void 0:s[6],a),minutes:e(s==null?void 0:s[7],a),seconds:e(s==null?void 0:s[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},kt=(i,e)=>{let t=i;t=Br(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(s)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Br(t,o,(l,c)=>r.isNullable(n)?l:r.isNullable(c)?n:n.padStart(parseInt(c,10),"0"))}return t},fm=(i,e)=>{var t,s,a,n,o,l,c,u,h,d,f,p,v,m,S,b,y,T,E,$,N,O,V,R,F,j,C,w,Y,L,A,U,Q,X,te,Ee,Nt,ht,B,se,oe,le;const Ot=new DOMParser().parseFromString(i,"application/xml"),De={video:[],audio:[],text:[]},de=Ot.children[0],pt=de.getElementsByTagName("Period")[0],Mt=(a=(s=(t=de.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&a!==void 0?a:"",ho=pt.children,fo=de.getAttribute("type")==="dynamic",$a=de.getAttribute("availabilityStartTime"),po=$a?new Date($a).getTime():void 0;let ze;const ka=de.getAttribute("mediaPresentationDuration"),Aa=pt.getAttribute("duration"),Hi=de.getElementsByTagName("vk:Attrs")[0],wa=Hi==null?void 0:Hi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ka)ze=Vr(ka);else if(Aa){const ce=Vr(Aa);r.isNonNullable(ce)&&(ze=ce)}else wa&&(ze=parseInt(wa,10));let mo=0;const Gi=(o=(n=de.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],vo=Gi.includes(Ci.WEBM_AS_IN_FFMPEG)||Gi.includes(Ci.WEBM_AS_IN_SPEC)?Lt.WEBM:Lt.MP4;for(const ce of ho){const Jt=ce.getAttribute("mimeType"),So=ce.getAttribute("codecs"),Pa=(l=ce.getAttribute("contentType"))!==null&&l!==void 0?l:Jt==null?void 0:Jt.split("/")[0],bo=(u=(c=ce.getAttribute("profiles"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[],Ca=ce.querySelectorAll("Representation"),go=ce.querySelector("SegmentTemplate");if(Pa===ie.TEXT){for(const Z of Ca){const Ue=Z.getAttribute("id")||"",Xt=ce.getAttribute("lang"),mt=ce.getAttribute("label"),Yi=(f=(d=(h=Z.querySelector("BaseURL"))===null||h===void 0?void 0:h.textContent)===null||d===void 0?void 0:d.trim())!==null&&f!==void 0?f:"",qi=new URL(Yi||Mt,e).toString(),Zt=Ue.includes("_auto");De[ie.TEXT].push({id:Ue,lang:Xt,label:mt,isAuto:Zt,kind:ie.TEXT,url:qi})}continue}for(const Z of Ca){const Ue=(p=Z.getAttribute("mimeType"))!==null&&p!==void 0?p:Jt,Xt=(m=(v=Z.getAttribute("codecs"))!==null&&v!==void 0?v:So)!==null&&m!==void 0?m:"",mt=(b=(S=Z.getAttribute("contentType"))!==null&&S!==void 0?S:Ue==null?void 0:Ue.split("/")[0])!==null&&b!==void 0?b:Pa,Yi=(T=(y=ce.getAttribute("profiles"))===null||y===void 0?void 0:y.split(","))!==null&&T!==void 0?T:[],qi=parseInt((E=Z.getAttribute("width"))!==null&&E!==void 0?E:"",10),Zt=parseInt(($=Z.getAttribute("height"))!==null&&$!==void 0?$:"",10),La=parseInt((N=Z.getAttribute("bandwidth"))!==null&&N!==void 0?N:"",10)/1e3,Da=(O=Z.getAttribute("frameRate"))!==null&&O!==void 0?O:"",yo=(V=Z.getAttribute("quality"))!==null&&V!==void 0?V:void 0,To=Da?hm(Da):void 0,Eo=(R=Z.getAttribute("id"))!==null&&R!==void 0?R:(mo++).toString(10),$o=mt==="video"?`${Zt}p`:mt==="audio"?`${La}Kbps`:Xt,ko=`${Eo}@${$o}`,Ao=(C=(j=(F=Z.querySelector("BaseURL"))===null||F===void 0?void 0:F.textContent)===null||j===void 0?void 0:j.trim())!==null&&C!==void 0?C:"",xa=new URL(Ao||Mt,e).toString(),wo=[...Gi,...bo,...Yi];let zi;const Po=Z.querySelector("SegmentBase"),We=(w=Z.querySelector("SegmentTemplate"))!==null&&w!==void 0?w:go;if(Po){const Qe=(L=(Y=Z.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&L!==void 0?L:"",[Ke,Qi]=Qe.split("-").map(vt=>parseInt(vt,10)),je={from:Ke,to:Qi},Bt=(A=Z.querySelector("SegmentBase"))===null||A===void 0?void 0:A.getAttribute("indexRange"),[Ki,ei]=Bt?Bt.split("-").map(vt=>parseInt(vt,10)):[],Vt=Bt?{from:Ki,to:ei}:void 0;zi={type:pe.BYTE_RANGE,url:xa,initRange:je,indexRange:Vt}}else if(We){const Qe={representationId:(U=Z.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(Q=Z.getAttribute("bandwidth"))!==null&&Q!==void 0?Q:void 0},Ke=parseInt((X=We.getAttribute("timescale"))!==null&&X!==void 0?X:"",10),Qi=(te=We.getAttribute("initialization"))!==null&&te!==void 0?te:"",je=We.getAttribute("media"),Bt=(Nt=parseInt((Ee=We.getAttribute("startNumber"))!==null&&Ee!==void 0?Ee:"",10))!==null&&Nt!==void 0?Nt:1,Ki=kt(Qi,Qe);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");const ei=(ht=We.querySelectorAll("SegmentTimeline S"))!==null&&ht!==void 0?ht:[],Vt=[];let vt=0,Ji="",Xi=0;if(ei.length){let ti=Bt,ve=0;for(const St of ei){const $e=parseInt((B=St.getAttribute("d"))!==null&&B!==void 0?B:"",10),Je=parseInt((se=St.getAttribute("r"))!==null&&se!==void 0?se:"",10)||0,ii=parseInt((oe=St.getAttribute("t"))!==null&&oe!==void 0?oe:"",10);ve=Number.isFinite(ii)?ii:ve;const Zi=$e/Ke*1e3,es=ve/Ke*1e3;for(let si=0;si<Je+1;si++){const Lo=kt(je,{...Qe,segmentNumber:ti.toString(10),segmentTime:(ve+si*$e).toString(10)}),_a=(es!=null?es:0)+si*Zi,Do=_a+Zi;ti++,Vt.push({time:{from:_a,to:Do},url:Lo})}ve+=(Je+1)*$e,vt+=(Je+1)*Zi}Xi=ve/Ke*1e3,Ji=kt(je,{...Qe,segmentNumber:ti.toString(10),segmentTime:ve.toString(10)})}else if(r.isNonNullable(ze)){const ve=parseInt((le=We.getAttribute("duration"))!==null&&le!==void 0?le:"",10)/Ke*1e3,St=Math.ceil(ze/ve);let $e=0;for(let Je=1;Je<St;Je++){const ii=kt(je,{...Qe,segmentNumber:Je.toString(10),segmentTime:$e.toString(10)});Vt.push({time:{from:$e,to:$e+ve},url:ii}),$e+=ve}Xi=$e,Ji=kt(je,{...Qe,segmentNumber:St.toString(10),segmentTime:$e.toString(10)})}const Co={time:{from:Xi,to:1/0},url:Ji};zi={type:pe.TEMPLATE,baseUrl:xa,segmentTemplateUrl:je,initUrl:Ki,totalSegmentsDurationMs:vt,segments:Vt,nextSegmentBeyondManifest:Co,timescale:Ke}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!mt||!Ue)continue;const Wi={video:ie.VIDEO,audio:ie.AUDIO,text:ie.TEXT}[mt];Wi&&De[Wi].push({id:ko,kind:Wi,segmentReference:zi,profiles:wo,duration:ze,bitrate:La,mime:Ue,codecs:Xt,width:qi,height:Zt,fps:To,quality:yo})}}return{dynamic:fo,liveAvailabilityStartTime:po,duration:ze,container:vo,representations:De}},pm=({id:i,width:e,height:t,bitrate:s,fps:a,quality:n})=>{var o;const l=(o=n?Fi(n):void 0)!==null&&o!==void 0?o:r.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:a}},mm=({id:i,bitrate:e})=>({id:i,bitrate:e}),vm=(i,e,t)=>{var s;const a=e.indexOf(t);return(s=xe(i,Math.round(i.length*a/e.length)))!==null&&s!==void 0?s:xe(i,-1)},Sm=({id:i,lang:e,label:t,url:s,isAuto:a})=>({id:i,url:s,isAuto:a,type:"internal",language:e,label:t}),Fr=i=>"url"in i,Et=i=>i.type===pe.TEMPLATE,Xs=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class Ur{constructor(e,t,s,a,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:c,compatibilityMode:u=!1,manifest:h}){switch(this.currentSegmentLength$=new r.ValueSubject(0),this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.playingRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ct,this.destroyAbortController=new Ct,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=r.abortable(this.destroyAbortController.signal,async function*(d){const f=this.representations.get(d);r.assertNonNullable(f,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${f.mime}; codecs="${f.codecs}"`),this.sourceBufferTaskQueue=new Yf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(S=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,_r(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield this.loadInit(f,"high",!0);const p=this.initData.get(f.id),v=this.segments.get(f.id),m=this.parsedInitData.get(f.id);r.assertNonNullable(p,"No init buffer for starting representation"),r.assertNonNullable(v,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(v,f),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(d){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return;this.switchingToRepresentationId=d;const f=this.representations.get(d);r.assertNonNullable(f,`No such representation ${d}`);let p=this.segments.get(d),v=this.initData.get(d);if(r.isNullable(v)||r.isNullable(p)?yield this.loadInit(f,"high",!1):v instanceof Promise&&(yield v),p=this.segments.get(d),r.assertNonNullable(p,"No segments for starting representation"),v=this.initData.get(d),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal);const m=this.getCurrentPosition();r.isNonNullable(m)&&(this.isLive||(p.forEach(S=>S.status=D.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=r.abortable(this.destroyAbortController.signal,async function*(d){var f;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!d)return;for(const y of this.representations.keys()){const T=d.find(N=>N.id===y);T&&this.representations.set(y,T);const E=this.representations.get(y);if(!E||!Et(E.segmentReference))return;const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,v=this.representations.get(p);r.assertNonNullable(v);const m=this.segments.get(p);r.assertNonNullable(m,"No segments for starting representation");const S=this.initData.get(p);if(r.assertNonNullable(S,"No init buffer for starting representation"),!(S instanceof ArrayBuffer))return;const b=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),b&&(yield this.sourceBufferTaskQueue.remove(b.from*1e3,b.to*1e3,this.destroyAbortController.signal)),this.searchGaps(m,v),yield this.sourceBufferTaskQueue.append(S,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=c,this.isLive=!!(h!=null&&h.dynamic),this.container=s,s){case Lt.MP4:this.containerParser=bp;break;case Lt.WEBM:this.containerParser=Ap;break;default:r.assertNever(s)}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(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ct,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var t,s;if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const a=this.representations.get(this.downloadingRepresentationId),n=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(a,`No such representation ${this.downloadingRepresentationId}`),!n)return;const o=n.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((t=o==null?void 0:o.time.to)!==null&&t!==void 0?t:0)-((s=o==null?void 0:o.time.from)!==null&&s!==void 0?s:0));let l=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const f=jt(this.sourceBuffer.buffered,e),p=o?o.time.to+100:-1/0;o&&o.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&f>=o.time.to-e+100&&(l=p)}if(isFinite(this.bufferLimit)&&_r(this.sourceBuffer.buffered)>=this.bufferLimit){const d=jt(this.sourceBuffer.buffered,e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<f);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(n,a.segmentReference.type,l),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&o)if(u.includes(o))d="high";else{const f=xe(u,0);f&&f.time.from-o.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,a,d)}(!this.preloadOnly&&!this.allInitsLoaded&&o&&o.status===D.FED&&!u.length&&jt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const h=xe(n,-1);h&&h.status===D.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(o===h))}searchGaps(e,t){this.gaps=[];let s=0;const a=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:n.time.from+a}),s=n.time.to;r.isNonNullable(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,a=[];let n=0,o=t.length-1;do a.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<s&&o>=0);return this.liveInitialAdditionalOffset=n-s,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(a=>a.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,a,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Et(o.segmentReference))return;const l=o.segmentReference.segments.map(d=>({...d,status:D.NONE,size:void 0})),c=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(a=xe(c,-1))===null||a===void 0?void 0:a.time.to)!==null&&n!==void 0?n:0,h=l==null?void 0:l.findIndex(d=>Math.floor(u)>=Math.floor(d.time.from)&&Math.floor(u)<=Math.floor(d.time.to));if(h===-1){this.liveUpdateSegmentIndex=0;const d=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,d)}else{const d=l.slice(h+1);this.segments.set(o.id,[...c,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const a=s.segmentReference;if(!Et(a))return;const n=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),o=kt(a.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],c=l.find(h=>Math.floor(h.time.from)===Math.floor(e.segment.time.from));c&&(c.time.to=e.segment.time.to),!!l.find(h=>Math.floor(h.time.from)===Math.floor(e.segment.time.to))||l.push({status:D.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,s,a;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(c=>c.time.from<=e&&c.time.to>=e);return(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a: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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const a=e.findIndex(({status:d,time:{from:f,to:p}},v)=>{const m=f<=s&&p>=s,S=f>s||m||v===0&&s===0,b=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+b||p<=s+b;return(d===D.NONE||d===D.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Js(this.sourceBuffer.buffered,s))&&S&&y});if(a===-1)return[];if(t!==pe.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,l=0;const c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=u||l<=h);d++){const f=n[d];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===D.NONE||f.status===D.PARTIALLY_EJECTED)c.push(f);else break}return c}async loadSegments(e,t,s="auto"){t.segmentReference.type===pe.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=D.DOWNLOADING;const a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);const{range:n,url:o,signal:l,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(await r.abortable(l,async function*(){const h=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(o,{range:n,signal:l,onProgress:c,priority:s,isLowLatency:this.isActiveLowLatency()});if(!h)return;const d=new DataView(h);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,f)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,l),a.segment.status=D.DOWNLOADED,this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Xs(h)||this.failedDownloads++}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const c of e)c.status=D.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:a,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const c=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,c),r.fromEvent(window,"online").pipe(r.once()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:a,onProgress:l,signal:o,priority:s}),this.failedDownloads=0}catch(c){this.abortActiveSegments(e),Xs(c)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Et(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,a={from:xe(e,0).byte.from,to:xe(e,-1).byte.to},{signal:n}=this.downloadAbortController;return{url:s,range:a,signal:n,onProgress:(l,c)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:l,loaded:c,signal:n,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Et(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 a=s.toString(),{signal:n}=this.downloadAbortController,o=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,h)=>{if(!n.aborted)try{const d=this.onSomeTemplateDataLoaded({dataView:u,loaded:h,signal:n,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});o.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:n,onProgress:c,onProgressTasks:o}}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:a,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:c}=l;if(l.representationId===t){if(n.aborted){a();continue}if(l.loadedBytes=s,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);h!=null&&h.byteLength&&(c.status=D.PARTIALLY_FED,l.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),l.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:a,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const c=l.segmentReference.type,u=e.byteLength;for(const h of this.activeSegments){const{segment:d}=h,f=c===pe.BYTE_RANGE,p=f?d.byte.to-d.byte.from+1:u;if(h.representationId!==t||!(!f||d.byte.from>=s&&d.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const m=f?d.byte.from-s:0,S=f?d.byte.to-s:e.byteLength,b=m<a,y=S<=a;if(d.status===D.DOWNLOADING&&b&&y){d.status=D.DOWNLOADED;const T=new DataView(e.buffer,e.byteOffset+m,p);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?this.onSegmentFullyAppended(h,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&b&&(h.loadedBytes=Math.min(p,a-m),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+m+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===p?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(d.status=D.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then($=>{if(n.aborted)o();else if($)h.fedBytes+=E.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=D.FED,Fr(e.segment)&&(e.segment.size=e.fedBytes);for(const a of this.representations.values())if(a.id!==t)for(const n of(s=this.segments.get(a.id))!==null&&s!==void 0?s:[])n.status===D.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=D.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===D.PARTIALLY_FED||e.status===D.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=D.NONE),e.status=D.PARTIALLY_EJECTED):e.status=D.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[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=xr(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async l=>{if(!l)return;const{init:c,dataView:u,segments:h}=l,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let f=h;this.isLive&&Et(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=0,n=1/0,o=-1/0,l=!1;const c=u=>{var h;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const d=Fr(u)?(h=u.size)!==null&&h!==void 0?h:0:u.byte.to-u.byte.from;a+=d};for(const u of this.segments.values())for(const h of u){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;h.status===D.FED&&c(h)}if(l=isFinite(n)&&isFinite(o),!l){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const h of u){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;h.status===D.FED&&c(h)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const h=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===D.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(d)){n=h,o=d;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const d of h)d.time.from>e+u&&d.status===D.FED&&c(d)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let a={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){a=void 0;break}l>s.time.from&&l<s.time.to&&(a.from=l),o<s.time.to&&o>s.time.from&&(a.to=o)}}a&&a.to-a.from>1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=xr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const a=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:a,to:n})}const t=1;for(const s of this.segments.values())for(const a of s){const{status:n}=a;if(n!==D.FED&&n!==D.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),c=e.some(h=>h.from-t<=o&&h.to+t>=l),u=e.filter(h=>o>=h.from-t&&o<=h.to+t||l>=h.from-t&&l<=h.to+t);c||(u.length===1||this.gaps.some(h=>h.from===a.time.from||h.to===a.time.to)?a.status=D.PARTIALLY_EJECTED:a.status=D.NONE)}}}var Zs=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},bm=i=>{var e,t;const s=i.get("X-Delivery-Type"),a=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Pt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pt||(Pt={}));class gm{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new Ct,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=Zs(n));const o=yield Yt(n,{signal:this.abortAllController.signal}).catch(Ft);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:o,onProgress:l,priority:c="auto",signal:u,measureThroughput:h=!0,isLowLatency:d=!1}={}){var f,p;let v=a;const m=new Headers;if(o)switch(n){case Pt.HEADER:{m.append("Range",`bytes=${o.from}-${o.to}`);break}case Pt.PARAM:{const w=new URL(v,location.href);w.searchParams.append("bytes",`${o.from}-${o.to}`),v=w.toString();break}default:r.assertNever(n)}this.requestQuic&&(v=Zs(v));let S=this.abortAllController.signal,b;if(u){const w=new Ct;if(b=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{w.abort()}catch(Y){Ft(Y)}}),this.abortAllController.signal.aborted||u.aborted)try{w.abort()}catch(Y){Ft(Y)}S=w.signal}const y=r.now(),T=yield Yt(v,{priority:c,headers:m,signal:S}).catch(Ft),E=r.now();if(!T)return b==null||b.unsubscribe(),null;if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(E-y),!T.ok||!T.body)return b==null||b.unsubscribe(),Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`));if(this.onHeadersReceived(T.headers),!l&&!h)return b==null||b.unsubscribe(),T.arrayBuffer();const[$,N]=T.body.tee(),O=$.getReader();h&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(N,d));let V=0,R=new Uint8Array(0),F=!1;const j=w=>{b==null||b.unsubscribe(),F=!0,Ft(w)},C=r.abortable(S,async function*({done:w,value:Y}){if(V===0&&this.lastRequestFirstBytes$.next(r.now()-y),S.aborted){b==null||b.unsubscribe();return}if(!w&&Y){const L=new Uint8Array(R.length+Y.length);L.set(R),L.set(Y,R.length),R=L,V+=Y.byteLength,l==null||l(new DataView(R.buffer),V),yield O==null?void 0:O.read().then(C,j)}}.bind(this));return yield O==null?void 0:O.read().then(C,j),b==null||b.unsubscribe(),F?null:R.buffer}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==pe.BYTE_RANGE)return null;const{from:c,to:u}=a.initRange;let h=c,d=u,f=!1,p,v;a.indexRange&&(p=a.indexRange.from,v=a.indexRange.to,f=u+1===p,f&&(h=Math.min(p,c),d=Math.max(v,u))),h=Math.min(h,0);const m=yield this.fetch(a.url,{range:{from:h,to:d},priority:o,measureThroughput:!1});if(!m)return null;const S=new DataView(m,c-h,u-h+1);if(!n.validateData(S))throw new Error("Invalid media file");const b=n.parseInit(S),y=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(b);if(!y)throw new ReferenceError("No way to load representation index");let T;if(f)T=new DataView(m,y.from-h,y.to-y.from+1);else{const $=yield this.fetch(a.url,{range:y,priority:o,measureThroughput:!1});if(!$)return null;T=new DataView($)}const E=n.parseSegments(T,b,y);return{init:b,dataView:new DataView(m),segments:E}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==pe.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:a.segments.map(u=>({...u,status:D.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=bm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var a,n;const{type:o}=e;switch(o){case pe.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,s))!==null&&a!==void 0?a:null;case pe.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ft=i=>{if(!Xs(i))throw i},At=1e3,xi=(i,e,t)=>t*e+(1-t)*i,ro=(i,e)=>i.reduce((t,s)=>t+s,0)/e,ym=(i,e,t,s)=>{let a=0,n=t;const o=ro(i,e),l=e<s?e:s;for(let c=0;c<l;c++)i[n]>o?a++:a--,n=(i.length+n-1)%i.length;return Math.abs(a)===l};class Ta{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 r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(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 l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=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>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Tm extends Ta{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=xi(this.slow,e,this.params.emaAlphaSlow),this.fast=xi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Em extends Ta{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ro(this.pastMeasures,this.takenMeasures);this.emaSmoothed=xi(this.emaSmoothed,e,this.params.emaAlpha);const s=ym(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class $m extends Ta{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?xi(this.smoothed,e,this.params.emaAlpha):e}}class ea{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Tm({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Em({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 $m({initial:e,label:"liveEdgeDelay",...t})}}const km=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Xe=()=>window.ManagedMediaSource||window.MediaSource,no=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Am=()=>{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))},wm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,jr=["timeupdate","progress","play","seeked","stalled","waiting"];var fe;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(fe||(fe={}));let Pm=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.representationSubscription=new r.Subscription,this.state$=new J(fe.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.currentVideoRepresentationInit$=new r.ValueSubject(void 0),this.currentVideoSegmentLength$=new r.ValueSubject(0),this.currentAudioSegmentLength$=new r.ValueSubject(0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.isLive$=new r.ValueSubject(!1),this.liveDuration$=new r.ValueSubject(0),this.liveAvailabilityStartTime$=new r.ValueSubject(void 0),this.bufferLength$=new r.ValueSubject(0),this.liveLoadBufferLength$=new r.ValueSubject(0),this.livePositionFromPlayer$=new r.ValueSubject(0),this.timeInWaiting=0,this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ct,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,s,a){var n;this.element=t,this.manifestUrlString=ge(s,a,ee.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(fe.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(fe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=r.abortable(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!s)return null;let a;try{a=fm(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return null;const n=({kind:o,mime:l,codecs:c})=>{var u,h,d,f;return!!(!((h=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||h===void 0)&&h.call(u,l)&&(!((f=(d=Xe())===null||d===void 0?void 0:d.isTypeSupported)===null||f===void 0)&&f.call(d,`${l}; codecs="${c}"`))||o===ie.TEXT)};return a.dynamic&&this.isLive$.getValue()!==a.dynamic&&(this.isLive$.next(a.dynamic),this.liveDuration$.getValue()!==a.duration&&this.liveDuration$.next(-1*((t=a.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==a.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(a.liveAvailabilityStartTime)),{...a,representations:Pi(Object.entries(a.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,s,a){var n;r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(fe.REPRESENTATIOS_READY);const o=m=>{this.representationSubscription.add(r.fromEvent(m,"error").pipe(r.filter(S=>{var b;return!!(!((b=this.element)===null||b===void 0)&&b.played.length)})).subscribe(S=>{this.error$.next({id:"VideoSource",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:S})}))};this.source=this.tuning.useManagedMediaSource?wm():new MediaSource;const l=document.createElement("source");if(o(l),l.src=URL.createObjectURL(this.source),this.element.appendChild(l),this.tuning.useManagedMediaSource&&no())if(a){const m=document.createElement("source");o(m),m.type="application/x-mpegurl",m.src=a.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const c={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 Ur(ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,c),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(s)&&(this.audioBufferManager=new Ur(ie.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,c),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(r.interval(At).subscribe(m=>{var S;if(!((S=this.element)===null||S===void 0)&&S.paused){const b=Ar(this.manifestUrlString,ee.DASH_CMAF_OFFSET_P);this.manifestUrlString=ge(this.manifestUrlString,b+At,ee.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...jr.filter(m=>m!=="waiting").map(m=>r.fromEvent(this.element,m))).pipe(r.map(m=>this.element?jt(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(m=>!!m),r.tap(m=>{var S;(S=this.stallWatchdogSubscription)===null||S===void 0||S.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(S=>this.isActiveLowLatency&&!!S)).subscribe(S=>this.liveEstimatedDelay.next(S))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(S=>{if(!this.isActiveLowLatency)return;const b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=S-b;let $=1+Math.sign(E)*T;Math.abs(E)<y?$=1:Math.abs(E)>y*2&&($=1+Math.sign(E)*T*2),km(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(S=>{var b,y;let T=0;if(S){const E=((y=(b=this.element)===null||b===void 0?void 0:b.currentTime)!==null&&y!==void 0?y:0)*1e3;T=Math.min(...this.bufferManagers.map(N=>{var O,V;return(V=(O=N.getLiveSegmentsToLoadState(this.manifest))===null||O===void 0?void 0:O.to)!==null&&V!==void 0?V:E}))-E}this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let m=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(r.throttle(At)).subscribe(async({liveLoadBufferLength:S,bufferLength:b})=>{if(r.assertNonNullable(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,T=Ar(this.manifestUrlString,ee.DASH_CMAF_OFFSET_P),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),N=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,O=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,V=this.isActiveLowLatency?b:S;let R=Ae.None;if(this.isActiveLowLatency?R=Ae.ActiveLowLatency:V<$+O&&V>=$?R=Ae.LiveWithTargetOffset:T!==0&&V<$&&(R=Ae.LiveForwardBuffering),isFinite(S)&&(m=S>m?S:m),R===Ae.LiveForwardBuffering||R===Ae.LiveWithTargetOffset){const F=m-($+N),j=this.normolizeLiveOffset(Math.trunc(T+F/y)),C=Math.abs(j-T);let w;!S||C<=this.tuning.dashCmafLive.offsetCalculationError?w=T:j>0&&C>this.tuning.dashCmafLive.offsetCalculationError?w=j:w=0,this.manifestUrlString=ge(this.manifestUrlString,w,ee.DASH_CMAF_OFFSET_P)}R!==Ae.None&&R!==Ae.ActiveLowLatency&&(m=0,this.updateLive())}))}const u=r.merge(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),h=r.merge(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:u,someBufferEnded:h}).pipe(r.filter(({allBuffersFull:m,someBufferEnded:S})=>m&&S))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(S=>!S.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(S){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:S})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(m=>{var S;return(S=this.source)===null||S===void 0?void 0:S.addEventListener("sourceopen",m)}));const d=(n=this.manifest.duration)!==null&&n!==void 0?n:0,f=(m,S)=>{var b;return Math.max(m,(b=S.duration)!==null&&b!==void 0?b:0)},p=this.manifest.representations.audio.reduce(f,d),v=this.manifest.representations.video.reduce(f,d);(p||v)&&(this.source.duration=Math.max(p,v)/1e3),this.audioBufferManager&&r.isNonNullable(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(fe.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new gm({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ea.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,a,n;r.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.manifestUrlString=ge(this.manifestUrlString,o,ee.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((a=this.audioBufferManager)===null||a===void 0?void 0:a.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)))}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(fe.RUNNING),this.subscription.add(r.merge(...jr.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{var e;this.element&&this.element.readyState===2&&!this.element.seeking&&Js(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const t=()=>{if(this.element){if(this.timeInWaiting+=At,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=r.interval(At).subscribe(t,s=>{this.error$.next({id:"StallWatchdogCallback",category:r.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){const s={[ie.VIDEO]:this.videoBufferManager,[ie.AUDIO]:this.audioBufferManager,[ie.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,a,n,o,l;r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let c;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?c=e:c=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Js(this.element.buffered,c)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(c),(l=this.audioBufferManager)===null||l===void 0||l.maintain(c),this.element.currentTime=c/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||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===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(fe.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=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const n of this.bufferManagers)for(const o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-a<=t&&o.to+a>t&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){const n=Math.max(...s)+10;n===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=n/1e3}}};class Cm{constructor(e,t){this.fov=e,this.orientation=t}}class Lm{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 a=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:a,y:n,z:o},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 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*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 Dm=`#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;}`,xm=`#ifdef GL_ES
39
- precision highp float;precision highp int;
33
+ [best track] ${U==null?void 0:U.quality}
34
+ [selected track] ${_==null?void 0:_.quality}
35
+ `});let Z=_&&u&&u.history[_.id]&&(0,F.now)()-u.history[_.id]<=r.trackCooldown&&(!u.last||_.id!==u.last.id);if(_!=null&&_.id&&u&&!Z&&u.recordSelection(_),Z&&(u!=null&&u.last)){let B=u.last;return u==null||u.recordSwitch(B),d({message:`
36
+ [last selected] ${B==null?void 0:B.quality}
37
+ `}),B}return u==null||u.recordSwitch(_),_},wt=GE;var le=i=>new URL(i).hostname;var O=require("@vkontakte/videoplayer-shared");var of=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"))},xe=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!of(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return of(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var Ae=require("@vkontakte/videoplayer-shared");var Xe=require("@vkontakte/videoplayer-shared");function ce(){return(0,Xe.now)()}function Po(i){return ce()-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 uf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Tr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,m="arraybuffer",f=7e3,g=2e3,S=()=>{if(l)return;(0,Xe.assertNonNullable)(c);let M=Po(c),ie;if(M<g){ie=g-M,setTimeout(S,ie);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new a,W()},y=M=>(s=M,G),v=M=>(d=M,G),w=()=>(m="json",G),E=()=>{if(!l){if(--u>=0){S(),r&&r();return}l=!0,d&&d(),t&&t()}},k=M=>(p=M,G),W=()=>{c=ce(),n=new a,n.open("get",i);let M=0,ie,me=0,B=()=>((0,Xe.assertNonNullable)(c),Math.max(c,Math.max(ie||0,me||0)));if(s&&n.addEventListener("progress",A=>{let K=ce();s.updateChunk&&A.loaded>M&&(s.updateChunk(B(),A.loaded-M),M=A.loaded,ie=K)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(l)return;(0,Xe.assertNonNullable)(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let K=n.response.byteLength-M;K&&s.updateChunk&&s.updateChunk(B(),K)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let A=()=>{(0,Xe.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(me=ce(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=m,n.send(),G},G={withBitrateReporting:y,withParallel:k,withJSONResponse:w,withRetryCount:M=>(u=M,G),withRetryInterval:(M,ie)=>((0,Xe.isNonNullable)(M)&&(g=M),(0,Xe.isNonNullable)(ie)&&(f=ie),G),withTimeout:M=>(o=M,G),withFinally:v,send:W,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return G}var ii=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 ai=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=ce(),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=ce()-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=Tr(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=ce()}_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=ce();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 Ka=1e4,ko=3;var WE=6e4,QE=10,zE=1,KE=500,si=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 ii(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||(0,Ae.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{uf(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 ai(ko,Ka,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 E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,k,W)=>{l&&l.abort(),l=Tr(this.urlResolver.resolve(E,!1),k,W,()=>this._retryCallback()).withTimeout(Ka).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ko).withFinally(()=>{l=null}).send()},m=(E,k,W)=>{(0,Ae.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),k,W,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let k=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${k}=>${E}`),r.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let W=ce()-1e4,U=0;for(let Z=0;Z<this.bufferStates.length;Z++){let j=this.bufferStates[Z];E=Math.min(E,j.buf),j.ts<W&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${E} drop=${U} jitter=${this.sourceJitter}`);let _=E-zE;this.sourceJitter>=0?_-=this.sourceJitter/2:this.sourceJitter-=1,_>3?f(1.15):_>1?f(1.1):_>.3?f(1.05):f(1)}},y=E=>{let k,W=()=>k&&k.start?k.start.length:0,U=A=>k.start[A]/1e3,_=A=>k.dur[A]/1e3,Z=A=>k.fragIndex+A,j=(A,K)=>({chunkIdx:Z(A),startTS:U(A),dur:_(A),discontinuity:K}),G=()=>{let A=0;if(k&&k.dur){let K=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,oe=K;this.sourceJitter>1&&(oe+=this.sourceJitter-1);let he=k.dur.length-1;for(;he>=0&&(oe-=k.dur[he],!(oe<=0));--he);A=Math.min(he,k.dur.length-1-ae),A=Math.max(A,0)}return j(A,!0)},M=A=>{let K=W();if(!(K<=0)){if((0,Ae.isNonNullable)(A)){for(let ae=0;ae<K;ae++)if(U(ae)>A)return j(ae)}return G()}},ie=A=>{let K=W(),ae=A?A.chunkIdx+1:0,oe=ae-k.fragIndex;if(!(K<=0)){if(!A||oe<0||oe-K>QE)return t(`Resync: offset=${oe} bChunks=${K} chunk=`+JSON.stringify(A)),G();if(!(oe>=K))return j(ae-k.fragIndex,!1)}},me=(A,K,ae)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(A,!0,this.lowLatency),K,ae,()=>this._retryCallback()).withTimeout(Ka).withRetryCount(ko).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,K)=>{me(E,ae=>{if(!d())return;k=ae;let oe=!!k.lowLatency;oe!==this.lowLatency&&g(oe);let he=0;for(let tt=0;tt<k.dur.length;++tt)he+=k.dur[tt];he>0&&((0,Ae.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/k.dur.length)),a({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,A(M(K))},()=>this._handleNetworkError())},nextChunk:ie}},v=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,Ae.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:k,logger:W}=this.params,U=y(e.jidxUrl),_,Z,j,G,M=0,ie,me,B,A=()=>{ie&&(clearTimeout(ie),ie=void 0);let Q=Math.max(KE,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+Q,Pe=ce(),Re=Math.min(1e4,be-Pe);M=Pe;let gt=()=>{u||d()&&U.seek(()=>{d()&&(M=ce(),K(),A())})};Re>0?ie=window.setTimeout(()=>{this.paused?A():gt()},Re):gt()},K=()=>{let Q;for(;Q=U.nextChunk(G);)G=Q,Qi(Q);let be=U.nextChunk(j);if(be){if(j&&be.discontinuity){W("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}tt(be)}else A()},ae=(Q,be)=>{if(!d()||!this.sourceBuffer)return;let Pe,Re,gt,tr=vt=>{window.setTimeout(()=>{d()&&ae(Q,be)},vt)};if(this.sourceBuffer.updating)W("Source buffer is updating; delaying appendBuffer"),tr(100);else{let vt=ce(),Lt=k.currentTime;!this.paused&&k.buffered.length>1&&me===Lt&&vt-B>500&&(W("Stall suspected; trying to fix"),this._fixupStall()),me!==Lt&&(me=Lt,B=vt);let rr=this._getBufferSizeSec();if(rr>30)W(`Buffered ${rr} seconds; delaying appendBuffer`),tr(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:vt,buf:rr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch($r){if($r.name==="QuotaExceededError")W("QuotaExceededError; delaying appendBuffer"),gt=this.sourceBuffer.buffered.length,gt!==0&&(Pe=this.sourceBuffer.buffered.start(0),Re=Lt,Re-Pe>4&&this.sourceBuffer.remove(Pe,Re-3)),tr(1e3);else throw $r}}},oe=()=>{Z&&_&&(W([`Appending chunk, sz=${Z.byteLength}:`,JSON.stringify(j)]),ae(Z,function(){Z=null,K()}))},he=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),tt=Q=>{d()&&m(he(Q),(be,Pe)=>{if(d()){if(Pe/=1e3,Z=be,j=Q,n=Q.startTS,Pe){let Re=Math.min(10,Q.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}oe()}},()=>this._handleNetworkError())},Qi=Q=>{d()&&((0,Ae.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(Q),!1)))},Lr=Q=>{d()&&(e.cachedHeader=Q,ae(Q,()=>{_=!0,oe()}))};s=!0,U.seek(Q=>{if(d()){if(M=ce(),!Q){A();return}G=Q,!(0,Ae.isNullable)(E)||Q.startTS>E?tt(Q):(j=Q,K())}},E),e.cachedHeader?Lr(e.cachedHeader):p(e.headerUrl,Lr,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Ae.isNonNullable)(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ae.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ae.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),f=d/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; 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,m)=>{let f=ce();if(this.chunkRateEstimator.addInterval(p,f,m)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-p,speed:S}),!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&&Po(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let m=s.updateChunk(d,p);return m&&u(),m},notifySwitch:d=>{let p=ce();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ka).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;xe(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))},WE))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var re=require("@vkontakte/videoplayer-shared"),Ao=class{constructor(){this.onDroopedVideoFramesLimit$=new re.Subject;this.subscription=new re.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new re.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,re.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,re.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,re.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,re.interval)(this.droppedFramesChecker.checkTime).pipe((0,re.filter)(()=>this.playing),(0,re.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,re.debounce)(this.droppedFramesChecker.checkTime)),r=(0,re.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,re.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ja=Ao;var Xa=require("@vkontakte/videoplayer-shared"),lf=require("@vkontakte/videoplayer-shared");var ni=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var JE=(i,e)=>new Xa.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||ni()))},{...r,...e});a.observe(i);let s=(0,lf.fromEvent)(document,"visibilitychange").pipe((0,Xa.map)(n=>!document.hidden||ni())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Me=JE;var XE=["paused","playing","ready"],ZE=["paused","playing","ready"],oi=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new De;this.droppedFramesManager=new Ja;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new nt;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:O.ErrorCategory.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=Pt(l.name))!=null?r:(0,O.videoSizeToQuality)(l.video),d=l.bitrate/1e3,p={...l.video};if(!c)continue;let m={id:u,quality:c,bitrate:d,size:p};o.push({track:m,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),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ZE.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&XE.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(pe(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(pe(this.params.source.url,l))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ye(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(le(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=Ee(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe((0,O.map)(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(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(Me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,O.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(a.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Te(this.video)}createLiveDashPlayer(){let e=new si({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,m,f;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&&(0,O.isNonNullable)(t)?t:wt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(m=this.params.desiredState.videoTrack.getState())==null?void 0:m.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let g=(f=e.find(({track:S})=>S.id===s))==null?void 0:f.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(pe(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var cf=oi;var kt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var C=require("@vkontakte/videoplayer-shared");var Za=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}},Ir=class extends Za{constructor(){super(),this.listeners||Za.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)}},ui=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,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&&(ui.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function es(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 Ro(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!es({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(m){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((m,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var li=es({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),df=li?Ro({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=li?df.fetch:window.fetch,$L=li?df.Request:window.Request,ct=li?ui:window.AbortController,CL=li?Ir:window.AbortSignal;var cm=Ne(Ma(),1);var ci=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var T=require("@vkontakte/videoplayer-shared");var kr=Ne(Qa(),1);var ex=(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)},tx=i=>window.clearTimeout(i),pf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Lo=pf?ex:window.requestIdleCallback,OL=pf?tx:window.cancelIdleCallback;var im=Ne(Ya(),1);var Oe=require("@vkontakte/videoplayer-shared"),rx=16,mf=!1,hf,ff;try{mf=(0,Oe.getCurrentBrowser)().browser===Oe.CurrentClientBrowser.Safari&&parseInt((ff=(hf=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:hf[1])!=null?ff:"",10)<=rx}catch(i){console.error(i)}var $o=class{constructor(e){this.bufferFull$=new Oe.Subject;this.error$=new Oe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Oe.ErrorCategory.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;mf&&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:Oe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Oe.assertNever)(t)}}},bf=$o;var Co=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var z=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 Er=class extends z{};var di=class extends z{};var pi=class extends z{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 hi=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends z{constructor(t,r){super(t,r);this.data=this.content}};var se=class extends z{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Ht=class extends se{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 bi=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends se{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 Si=class extends se{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var yi=class extends se{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ti=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends se{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 Ei=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends se{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var wi=class extends z{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends se{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 Ai=class extends se{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 Ri=class extends se{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 ax={ftyp:pi,moov:hi,moof:fi,mdat:mi,sidx:Ht,trak:bi,mdia:Ti,mfhd:Pi,tkhd:Ii,traf:wi,tfhd:ki,tfdt:Ai,trun:Ri,minf:Ei,sv3d:gi,st3d:vi,prhd:Si,proj:xi,equi:yi,uuid:di,unknown:Er},jt=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=ax[e];return r?new r(t,new i):new Er(t,new i)}};var xr=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 nx=new TextDecoder("ascii"),ox=i=>nx.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",ux=i=>{let e=new Ht(i,new jt),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})},lx=(i,e)=>{let r=new jt().parse(i),a=new xr(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)},cx=(i,e)=>{let r=new jt().parse(i),s=new xr(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},dx=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 jt().parse(i),a=new xr(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},gf={validateData:ox,parseInit:dx,getIndexRange:()=>{},parseSegments:ux,parseFeedableSegmentChunk:lx,getSegmentEndTime:cx};var dt=require("@vkontakte/videoplayer-shared");var Sf=require("@vkontakte/videoplayer-shared");var vf={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"}},yf=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=Li(i,t),a=r in vf,s=a?vf[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=Li(l),d=u*2**((o-1)*8)+c,p=t+o,m;return p+d>i.byteLength?m=new DataView(i.buffer,i.byteOffset+p):m=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:m,valueSize:d}},Li=(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},Ge=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Li(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:(0,Sf.assertNever)(e)}},Gt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=yf(r);if(!e(a))return;a.type==="master"&&Gt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Tf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=yf(i);return Gt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ge(o,n):s===17026?t=Ge(o,n):s===17029&&(r=Ge(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var If=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],px=[231,22612,22743,167,171,163,160,175],hx=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Gt(i,({tag:p,type:m,value:f,valueSize:g})=>{if(p===21419){let S=Ge(f,m);u=Li(S)}else p!==21420&&(u=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ge(f,m):p===17545?a=Ge(f,m):p===21420&&u===475249515?l=Ge(f,m):p===374648427?Gt(f,({tag:S,type:y,value:v})=>S===30321?(c=Ge(v,y)===1,!1):!0):s&&n&&If.includes(p)&&(o=!0),!o}),(0,dt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,dt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,dt.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},fx=i=>{if((0,dt.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},mx=(i,e)=>{let t=!1,r=!1,a=o=>(0,dt.isNonNullable)(o.time)&&(0,dt.isNonNullable)(o.position),s=[],n;return Gt(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=Ge(u,l));break;case 183:break;case 241:n&&(n.position=Ge(u,l));break;default:t&&If.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}}})},bx=i=>{let e=0,t=!1;try{Gt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):px.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},Ef={validateData:Tf,parseInit:hx,getIndexRange:fx,parseSegments:mx,parseFeedableSegmentChunk:bx};var _o=Ne(Wf(),1),wr=require("@vkontakte/videoplayer-shared");var Qf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var zf=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},Yt=(i,e)=>{let t=i;t=(0,_o.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,_o.default)(t,n,(o,l)=>(0,wr.isNullable)(s)?o:(0,wr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Jf=(i,e)=>{var E,k,W,U,_,Z,j,G,M,ie,me,B,A,K,ae,oe,he,tt,Qi,Lr,Q,be,Pe,Re,gt,tr,vt,Lt,rr,$r,Ko,Jo,Xo,Zo,eu,tu,ru,iu,au,su,nu,ou;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(W=(k=(E=s.querySelector("BaseURL"))==null?void 0:E.textContent)==null?void 0:k.trim())!=null?W:"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,m=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)p=zf(m);else if(f){let Le=zf(f);(0,wr.isNonNullable)(Le)&&(p=Le)}else S&&(p=parseInt(S,10));let y=0,v=(_=(U=s.getAttribute("profiles"))==null?void 0:U.split(","))!=null?_:[],w=v.includes("urn:webm:dash:profile:webm-on-demand:2012")||v.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let Le of l){let zi=Le.getAttribute("mimeType"),Qm=Le.getAttribute("codecs"),uu=(Z=Le.getAttribute("contentType"))!=null?Z:zi==null?void 0:zi.split("/")[0],zm=(G=(j=Le.getAttribute("profiles"))==null?void 0:j.split(","))!=null?G:[],lu=Le.querySelectorAll("Representation"),Km=Le.querySelector("SegmentTemplate");if(uu==="text"){for(let ne of lu){let St=ne.getAttribute("id")||"",Ki=Le.getAttribute("lang"),ir=Le.getAttribute("label"),ys=(me=(ie=(M=ne.querySelector("BaseURL"))==null?void 0:M.textContent)==null?void 0:ie.trim())!=null?me:"",Ts=new URL(ys||o,e).toString(),Ji=St.includes("_auto");a.text.push({id:St,lang:Ki,label:ir,isAuto:Ji,kind:"text",url:Ts})}continue}for(let ne of lu){let St=(B=ne.getAttribute("mimeType"))!=null?B:zi,Ki=(K=(A=ne.getAttribute("codecs"))!=null?A:Qm)!=null?K:"",ir=(oe=(ae=ne.getAttribute("contentType"))!=null?ae:St==null?void 0:St.split("/")[0])!=null?oe:uu,ys=(tt=(he=Le.getAttribute("profiles"))==null?void 0:he.split(","))!=null?tt:[],Ts=parseInt((Qi=ne.getAttribute("width"))!=null?Qi:"",10),Ji=parseInt((Lr=ne.getAttribute("height"))!=null?Lr:"",10),cu=parseInt((Q=ne.getAttribute("bandwidth"))!=null?Q:"",10)/1e3,du=(be=ne.getAttribute("frameRate"))!=null?be:"",Jm=(Pe=ne.getAttribute("quality"))!=null?Pe:void 0,Xm=du?Qf(du):void 0,Zm=(Re=ne.getAttribute("id"))!=null?Re:(y++).toString(10),eb=ir==="video"?`${Ji}p`:ir==="audio"?`${cu}Kbps`:Ki,tb=`${Zm}@${eb}`,rb=(vt=(tr=(gt=ne.querySelector("BaseURL"))==null?void 0:gt.textContent)==null?void 0:tr.trim())!=null?vt:"",pu=new URL(rb||o,e).toString(),ib=[...v,...zm,...ys],Is,ab=ne.querySelector("SegmentBase"),$t=(Lt=ne.querySelector("SegmentTemplate"))!=null?Lt:Km;if(ab){let Ct=($r=(rr=ne.querySelector("SegmentBase Initialization"))==null?void 0:rr.getAttribute("range"))!=null?$r:"",[Dt,xs]=Ct.split("-").map(ar=>parseInt(ar,10)),yt={from:Dt,to:xs},Cr=(Ko=ne.querySelector("SegmentBase"))==null?void 0:Ko.getAttribute("indexRange"),[Ps,Xi]=Cr?Cr.split("-").map(ar=>parseInt(ar,10)):[],Dr=Cr?{from:Ps,to:Xi}:void 0;Is={type:"byteRange",url:pu,initRange:yt,indexRange:Dr}}else if($t){let Ct={representationId:(Jo=ne.getAttribute("id"))!=null?Jo:void 0,bandwidth:(Xo=ne.getAttribute("bandwidth"))!=null?Xo:void 0},Dt=parseInt((Zo=$t.getAttribute("timescale"))!=null?Zo:"",10),xs=(eu=$t.getAttribute("initialization"))!=null?eu:"",yt=$t.getAttribute("media"),Cr=(ru=parseInt((tu=$t.getAttribute("startNumber"))!=null?tu:"",10))!=null?ru:1,Ps=Yt(xs,Ct);if(!yt)throw new ReferenceError("No media attribute in SegmentTemplate");let Xi=(iu=$t.querySelectorAll("SegmentTimeline S"))!=null?iu:[],Dr=[],ar=0,ws="",ks=0;if(Xi.length){let Zi=Cr,_e=0;for(let sr of Xi){let We=parseInt((au=sr.getAttribute("d"))!=null?au:"",10),Mt=parseInt((su=sr.getAttribute("r"))!=null?su:"",10)||0,ea=parseInt((nu=sr.getAttribute("t"))!=null?nu:"",10);_e=Number.isFinite(ea)?ea:_e;let As=We/Dt*1e3,Rs=_e/Dt*1e3;for(let ta=0;ta<Mt+1;ta++){let nb=Yt(yt,{...Ct,segmentNumber:Zi.toString(10),segmentTime:(_e+ta*We).toString(10)}),hu=(Rs!=null?Rs:0)+ta*As,ob=hu+As;Zi++,Dr.push({time:{from:hu,to:ob},url:nb})}_e+=(Mt+1)*We,ar+=(Mt+1)*As}ks=_e/Dt*1e3,ws=Yt(yt,{...Ct,segmentNumber:Zi.toString(10),segmentTime:_e.toString(10)})}else if((0,wr.isNonNullable)(p)){let _e=parseInt((ou=$t.getAttribute("duration"))!=null?ou:"",10)/Dt*1e3,sr=Math.ceil(p/_e),We=0;for(let Mt=1;Mt<sr;Mt++){let ea=Yt(yt,{...Ct,segmentNumber:Mt.toString(10),segmentTime:We.toString(10)});Dr.push({time:{from:We,to:We+_e},url:ea}),We+=_e}ks=We,ws=Yt(yt,{...Ct,segmentNumber:sr.toString(10),segmentTime:We.toString(10)})}let sb={time:{from:ks,to:1/0},url:ws};Is={type:"template",baseUrl:pu,segmentTemplateUrl:yt,initUrl:Ps,totalSegmentsDurationMs:ar,segments:Dr,nextSegmentBeyondManifest:sb,timescale:Dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ir||!St)continue;let Es={video:"video",audio:"audio",text:"text"}[ir];Es&&a[Es].push({id:tb,kind:Es,segmentReference:Is,profiles:ib,duration:p,bitrate:cu,mime:St,codecs:Ki,width:Ts,height:Ji,fps:Xm,quality:Jm})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,container:w,representations:a}};var Fo=Ne(Qa(),1);var Xf=require("@vkontakte/videoplayer-shared"),Zf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?Pt(s):void 0)!=null?o:(0,Xf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},em=({id:i,bitrate:e})=>({id:i,bitrate:e}),tm=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,Fo.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,Fo.default)(i,-1)},rm=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),qo=i=>"url"in i,Wt=i=>i.type==="template",$i=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ci=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ct;this.destroyAbortController=new ct;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,x.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new bf(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:x.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,Co(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.assertNonNullable)(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,x.assertNonNullable)(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,x.isNullable)(a)||(0,x.isNullable)(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();(0,x.isNonNullable)(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=(0,x.abortable)(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||!Wt(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,r=this.representations.get(t);(0,x.assertNonNullable)(r);let a=this.segments.get(t);(0,x.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(t);if((0,x.assertNonNullable)(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=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=gf;break;case"webm":this.containerParser=Ef;break;default:(0,x.assertNever)(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ct,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var u,c;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((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=kt(this.sourceBuffer.buffered,e),m=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=m)}if(isFinite(this.bufferLimit)&&Co(this.sourceBuffer.buffered)>=this.bufferLimit){let d=kt(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,kr.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&&kt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,kr.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;(0,x.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!Wt(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,kr.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(!Wt(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Yt(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:m}},f)=>{let g=p<=r&&m>=r,S=p>r||g||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=r+y||m<=r+y;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&!ci(this.sourceBuffer.buffered,r))&&S&&v});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,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(0,x.abortable)(o,async function*(){let c=(0,x.getExponentialDelay)(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]),$i(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(0,x.abortable)(n,async function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).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),$i(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Wt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,kr.default)(e,0).byte.from,to:(0,kr.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:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(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:x.ErrorCategory.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",m=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 g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,y=g<a,v=S<=a;if(d.status==="downloading"&&y&&v){d.status="downloaded";let w=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(w,s).then(E=>E&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(c.loadedBytes=Math.min(m,a-g),c.loadedBytes>c.feedingBytes)){let w=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),E=c.loadedBytes===m?w:this.containerParser.parseFeedableSegmentChunk(w);E!=null&&E.byteLength&&(d.status="partially_fed",c.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(k=>{if(s.aborted)n();else if(k)c.fedBytes+=E.byteLength,c.fedBytes===m&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<m)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",qo(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=Lo(()=>(0,im.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?(0,x.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,x.getExponentialDelay)(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&&Wt(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:x.ErrorCategory.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||(0,x.isNullable)(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=qo(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 m of p)if(m.status==="none"&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.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=Lo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),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 Di=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var am=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};var X=require("@vkontakte/videoplayer-shared");var ts=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.abortAllController=new ct;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Di(t));let r=yield lt(t,{signal:this.abortAllController.signal}).catch(Mi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=(0,X.abortable)(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 _,Z;let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let j=new URL(u,location.href);j.searchParams.append("bytes",`${r.from}-${r.to}`),u=j.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(u=Di(u));let d=this.abortAllController.signal,p;if(n){let j=new ct;if(p=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{j.abort()}catch(G){Mi(G)}}),this.abortAllController.signal.aborted||n.aborted)try{j.abort()}catch(G){Mi(G)}d=j.signal}let m=(0,X.now)(),f=yield lt(u,{priority:s,headers:c,signal:d}).catch(Mi),g=(0,X.now)();if(!f)return p==null||p.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(g-m),!f.ok||!f.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!a&&!o)return p==null||p.unsubscribe(),f.arrayBuffer();let[S,y]=f.body.tee(),v=S.getReader();o&&((Z=this.throughputEstimator)==null||Z.trackStream(y,l));let w=0,E=new Uint8Array(0),k=!1,W=j=>{p==null||p.unsubscribe(),k=!0,Mi(j)},U=(0,X.abortable)(d,async function*({done:j,value:G}){if(w===0&&this.lastRequestFirstBytes$.next((0,X.now)()-m),d.aborted){p==null||p.unsubscribe();return}if(!j&&G){let M=new Uint8Array(E.length+G.length);M.set(E),M.set(G,E.length),E=M,w+=G.byteLength,a==null||a(new DataView(E.buffer),w),yield v==null?void 0:v.read().then(U,W)}}.bind(this));return yield v==null?void 0:v.read().then(U,W),p==null||p.unsubscribe(),k?null:E.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,r){var y;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 m=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let g;if(l)g=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;g=new DataView(v)}let S=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(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}=am(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:(0,X.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Mi=i=>{if(!$i(i))throw i};var Qt=(i,e,t)=>t*e+(1-t)*i,Uo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,sm=(i,e,t,r)=>{let a=0,s=t,n=Uo(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};var Oi=require("@vkontakte/videoplayer-shared"),At=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 Oi.ValueSubject(e.initial),this.debounced$=new Oi.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`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)&&((0,Oi.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var rs=class extends At{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Qt(this.slow,t,this.params.emaAlphaSlow),this.fast=Qt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var is=class extends At{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Uo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Qt(this.emaSmoothed,t,this.params.emaAlpha);let a=sm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var as=class extends At{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?Qt(this.smoothed,t,this.params.emaAlpha):t}};var zt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new rs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new is({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 as({initial:e,label:"liveEdgeDelay",...t})}};var nm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var pt=()=>window.ManagedMediaSource||window.MediaSource,ss=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},om=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},um=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var lm=["timeupdate","progress","play","seeked","stalled","waiting"];var ns=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new T.Subscription;this.representationSubscription=new T.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.isLive$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new ct;this.initManifest=(0,T.abortable)(this.destroyController.signal,async function*(e,t,r){var a;this.element=e,this.manifestUrlString=pe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,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:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Jf(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var l,u,c,d;return!!((u=(l=this.element)==null?void 0:l.canPlayType)!=null&&u.call(l,n)&&((d=(c=pt())==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,cm.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))}}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,r){var m;(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=f=>{this.representationSubscription.add((0,T.fromEvent)(f,"error").pipe((0,T.filter)(g=>{var S;return!!((S=this.element)!=null&&S.played.length)})).subscribe(g=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:g})}))};this.source=this.tuning.useManagedMediaSource?um():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ss())if(r){let f=document.createElement("source");a(f),f.type="application/x-mpegurl",f.src=r.url,this.element.appendChild(f)}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 Ci("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)&&(this.audioBufferManager=new Ci("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,T.interval)(1e3).subscribe(f=>{var g;if((g=this.element)!=null&&g.paused){let S=vo(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,S+1e3,2)}})),this.representationSubscription.add((0,T.merge)(...lm.filter(f=>f!=="waiting").map(f=>(0,T.fromEvent)(this.element,f))).pipe((0,T.map)(f=>this.element?kt(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.filter)(f=>!!f),(0,T.tap)(f=>{var g;(g=this.stallWatchdogSubscription)==null||g.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe((0,T.filter)(g=>this.isActiveLowLatency&&!!g)).subscribe(g=>this.liveEstimatedDelay.next(g))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(g=>{if(!this.isActiveLowLatency)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=g-S,E=1+Math.sign(w)*v;Math.abs(w)<y?E=1:Math.abs(w)>y*2&&(E=1+Math.sign(w)*v*2),nm(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(g=>{var y,v;let S=0;if(g){let w=((v=(y=this.element)==null?void 0:y.currentTime)!=null?v:0)*1e3;S=Math.min(...this.bufferManagers.map(k=>{var W,U;return(U=(W=k.getLiveSegmentsToLoadState(this.manifest))==null?void 0:W.to)!=null?U:w}))-w}this.liveLoadBufferLength$.getValue()!==S&&this.liveLoadBufferLength$.next(S)}));let f=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(async({liveLoadBufferLength:g,bufferLength:S})=>{if((0,T.assertNonNullable)(this.element),this.isUpdatingLive)return;let y=this.element.playbackRate,v=vo(this.manifestUrlString,2),w=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(w,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,W=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,U=this.isActiveLowLatency?S:g,_=3;if(this.isActiveLowLatency?_=0:U<E+W&&U>=E?_=1:v!==0&&U<E&&(_=2),isFinite(g)&&(f=g>f?g:f),_===2||_===1){let Z=f-(E+k),j=this.normolizeLiveOffset(Math.trunc(v+Z/y)),G=Math.abs(j-v),M;!g||G<=this.tuning.dashCmafLive.offsetCalculationError?M=v:j>0&&G>this.tuning.dashCmafLive.offsetCalculationError?M=j:M=0,this.manifestUrlString=pe(this.manifestUrlString,M,2)}_!==3&&_!==0&&(f=0,this.updateLive())}))}let o=(0,T.merge)(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),l=(0,T.merge)(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add((0,T.merge)(this.forceEnded$,(0,T.combine)({allBuffersFull:o,someBufferEnded:l}).pipe((0,T.filter)(({allBuffersFull:f,someBufferEnded:g})=>f&&g))).subscribe(()=>{var f;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(g=>!g.updating))try{(f=this.source)==null||f.endOfStream()}catch(g){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:g})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(f=>f.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(f=>{var g;return(g=this.source)==null?void 0:g.addEventListener("sourceopen",f)}));let u=(m=this.manifest.duration)!=null?m:0,c=(f,g)=>{var S;return Math.max(f,(S=g.duration)!=null?S: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&&(0,T.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:T.ErrorCategory.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ts({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=zt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,a,s,n;(0,T.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=pe(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(){(0,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...lm.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ci(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:T.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}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;(0,T.assertNonNullable)(this.element),(0,T.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),ci(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 os=class{constructor(e,t){this.fov=e,this.orientation=t}};var us=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 dm=`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 pm=`#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 _m{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const 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 Cm(this.params.fov,this.params.orientation),this.cameraRotationManager=new Lm(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"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=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(a,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(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(Dm,this.gl.VERTEX_SHADER),s=this.createShader(xm,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 a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:s=a/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,a=this.camera.fov.y/180/2,n=e-s,o=t-a,l=e+s,c=t-a,u=e+s,h=t+a,d=e-s,f=t+a;return[n,o,l,c,u,h,d,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class oo{constructor(e){this.subscription=new r.Subscription,this.videoState=new J(W.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new qe,this.droppedFramesManager=new Wn,this.videoTracks$=new r.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Af,this.textTracks=[],this.syncPlayback=()=>{var t,s,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(c.state===I.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==W.STOPPED&&o!==exports.PlaybackState.STOPPED){const h=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(c.position-h,c.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case W.STOPPED:this.videoState.startTransitionTo(W.READY),this.prepare();return;case W.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case W.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),(a=this.liveOffset)===null||a===void 0||a.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}}},this.init3DScene=t=>{var s,a,n;if(this.scene3D)return;this.scene3D=new _m(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:((a=t.projectionData)===null||a===void 0?void 0:a.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=ot(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(Le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pm({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=dt(this.video),a=this.constructor.name,n=l=>{e.error$.next({id:a,category:r.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:n,connect:(l,c)=>this.subscription.add(l.subscribe(c,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(r.map(u=>u.map(({track:h})=>h)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Kt(this.video,t.isLooped,a)),this.subscription.add(ut(this.video,t.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Rt(this.video,t.playbackRate,s.playbackRateState$,a)),n(r.observeElementSize(this.video),this.elementSize$),n(It(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var h;if(u===fe.MANIFEST_READY){const d=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();r.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((b,y)=>y.bitrate-b.bitrate),v=Array.from(f.video).sort((b,y)=>y.bitrate-b.bitrate),m=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const b of p){const y=mm(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of v){const y=pm(b);if(y){d.push({track:y,representation:b});const T=!this.params.tuning.isAudioDisabled&&vm(p,v,b);T&&this.audioRepresentations.set(b.id,T)}}this.videoTracks$.next(d);for(const b of m){const y=Sm(b);y&&this.textTracks.push({track:y,representation:b})}this.params.output.availableVideoTracks$.next(d.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const S=this.selectVideoRepresentation();r.assertNonNullable(S),this.player.initRepresentations(S.id,(h=this.audioRepresentations.get(S.id))===null||h===void 0?void 0:h.id,this.params.sourceHls)}else u===fe.REPRESENTATIOS_READY&&(this.videoState.setState(W.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),h=this.player.state$.getTransition();if(u!==fe.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const d=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);const p=this.params.desiredState.autoVideoTrackSwitching.getState(),v=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let m=d.id;!this.params.output.elementVisible$.getValue()&&p&&(m=this.videoTracks$.getValue().map(b=>b.representation).sort((b,y)=>y.bitrate-b.bitrate).filter(b=>{const y=r.videoSizeToQuality(b),T=r.videoSizeToQuality(d);if(y&&T)return r.isLowerOrEqual(y,T)&&r.isLowerOrEqual(y,v)}).map(b=>b.id)[0]),this.player.switchRepresentation(ie.VIDEO,m).catch(o);const S=this.audioRepresentations.get(d.id);S&&this.player.switchRepresentation(ie.AUDIO,S.id).catch(o)}},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(r.filterChanged(),r.map(u=>{var h;return u&&((h=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===u))===null||h===void 0?void 0:h.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var h,d;if(u!=null&&u.is3dVideo&&(!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((d=this.params.tuning.spherical)===null||d===void 0)&&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);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const c=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,s,a,n,o,l;const c=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,h=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,d=this.params.output.currentVideoTrack$.getValue(),f=jt(this.video.buffered,this.video.currentTime*1e3),p=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(h&&!c&&(a=(s=this.audioRepresentations.get(h.id))===null||s===void 0?void 0:s.bitrate)!==null&&a!==void 0?a:0,d&&(o=(n=this.audioRepresentations.get(d.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=Ui(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:v,current:d,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),b=c?S!=null?S:h:h!=null?h:S;return b&&((l=this.videoTracks$.getValue().find(({track:y})=>y===b))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),lt(this.video)}}class Rm extends oo{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 Im extends oo{constructor(e){super(e),this.liveOffset=new va}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(r.combine({interval:r.interval(At),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var n;if(this.videoState.getState()===W.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(a-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&s===W.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,a)})}}const Se={};var M;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const $t=(i,e)=>new r.Observable(t=>{const s=(a,n)=>t.next(n);return i.on(e,s),()=>i.off(e,s)});class Nm{constructor(e){this.subscription=new r.Subscription,this.videoState=new J(M.INITIALIZING),this.textTracksManager=new qe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&this.seek(n.position),s){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(s)}},this.video=ot(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(Le(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),lt(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(Se.Hls=a.default,Se.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){r.assertNonNullable(Se.Hls,"hls.js not loaded"),this.hls=new Se.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(Se.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=dt(this.video),n=(u,h)=>this.subscription.add(u.subscribe(h,s));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Kt(this.video,e.isLooped,s)),this.subscription.add(ut(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Rt(this.video,e.playbackRate,a.playbackRateState$,s)),n(It(this.video),t.elementVisible$),this.subscription.add($t(this.hls,Se.Events.ERROR).subscribe(u=>{var h;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(h=u.err)===null||h===void 0?void 0:h.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},s)),n($t(this.hls,Se.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((h,d)=>{var f,p;const v=d.name||d.height.toString(10),{width:m,height:S}=d,b=(p=Fi((f=d.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:r.videoSizeToQuality({width:m,height:S});if(!b)return h;const y=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:v.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:m,height:S},fps:y};return this.trackLevels.set(v,{track:T,level:d}),h.push(T),h},[]))),t.availableVideoTracks$),n($t(this.hls,Se.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const h=[];for(const d of u.subtitleTracks){const f=d.name,p=d.attrs.URI||"",v=d.lang,m="internal";h.push({id:f,url:p,language:v,type:m})}e.internalTextTracks.startTransitionTo(h)}}),n($t(this.hls,Se.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>Le(u))),t.hostname$),n($t(this.hls,Se.Events.FRAG_CHANGED),u=>{var h,d,f,p;const{video:v,audio:m}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=v==null?void 0:v.endPTS)!==null&&h!==void 0?h:0)-((d=v==null?void 0:v.startPTS)!==null&&d!==void 0?d:0))*1e3),t.currentAudioSegmentLength$.next((((f=m==null?void 0:m.endPTS)!==null&&f!==void 0?f:0)-((p=m==null?void 0:m.startPTS)!==null&&p!==void 0?p:0))*1e3)}),this.subscription.add(_e(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const o=u=>{var h;return(h=Array.from(this.trackLevels.values()).find(({level:d})=>d===u))===null||h===void 0?void 0:h.track},l=$t(this.hls,Se.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(_e(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var h;if(r.isNullable(u))return;const d=(h=this.trackLevels.get(u.id))===null||h===void 0?void 0:h.level;if(!d)return;const f=this.hls.levels.indexOf(d),p=this.hls.currentLevel,v=this.hls.levels[p];!v||d.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:s})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await ct(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.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(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Hr="X-Playback-Duration";var Gr=async i=>{var e;const t=await Yt(i),s=await t.text(),a=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return a?parseInt(a,10):t.headers.has(Hr)?parseInt(t.headers.get(Hr),10):void 0};const Om=i=>{let e=null;if(i.QUALITY&&(e=Fi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=r.videoSizeToQuality({width:t,height:s})}return e!=null?e:null},Mm=(i,e)=>{var t,s;const a=i.split(`
46
- `),n=[],o=[];for(let l=0;l<a.length;l++){const c=a[l],u=c.match(/^#EXT-X-STREAM-INF:(.+)/),h=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!h)){if(u){const d=Pi(u[1].split(",").map(y=>y.split("="))),f=(t=d.QUALITY)!==null&&t!==void 0?t:`stream-${d.BANDWIDTH}`,p=Om(d);let v;d.BANDWIDTH&&(v=parseInt(d.BANDWIDTH,10)/1e3||void 0),!v&&d["AVERAGE-BANDWIDTH"]&&(v=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let S;if(d.RESOLUTION){const[y,T]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&T&&(S={width:y,height:T})}const b=new URL(a[++l],e).toString();p&&n.push({id:f,quality:p,url:b,bandwidth:v,size:S,fps:m})}if(h){const d=Pi(h[1].split(",").map(m=>m.split("=")).map(([m,S])=>[m,S.replace(/^"|"$/g,"")])),f=(s=d.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,v=d.NAME;f&&p&&o.push({type:"internal",id:p,label:v,language:p,url:f,isAuto:!1})}}}if(!n.length)throw new Error("Empty manifest");return{qualityManifests:n,textTracks:o}},Bm=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Cs=0;const Ea=async(i,e=i,t)=>{const a=await(await Yt(i)).text();Cs+=1;try{const{qualityManifests:n,textTracks:o}=Mm(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Cs<=t.manifestRetryMaxCount)return await Bm(r.getExponentialDelay(Cs-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ea(i,e,t)}return{qualityManifests:[],textTracks:[]}};var H;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(H||(H={}));class Vm{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new J(H.STOPPED),this.textTracksManager=new qe,this.manifests$=new r.ValueSubject([]),this.liveOffset=new va,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){a!==H.STOPPED&&(this.videoState.startTransitionTo(H.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(H.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(a===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(l||c||u){const f=this.videoState.getState();this.videoState.setState(H.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&d.state===I.Requested){this.videoState.startTransitionTo(H.READY),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case H.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case H.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},Ea(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:r.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.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(Le(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,a;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(a=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=o.getState())===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:"master",h=this.manifests$.getValue();if(!h.length)return;const d=l?"master":u;return l&&!c&&o.startTransitionTo(this.masterManifest),h.find(f=>f.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=dt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,s));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(ut(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),n(It(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===H.READY&&this.videoState.setState(H.READY),this.videoState.getState()===H.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Le(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===H.CHANGING_MANIFEST&&this.videoState.setState(c.to),l&&l.state===I.Requested&&this.seek(l.position)},s)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,c,u;const h=(u=(c=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||c===void 0?void 0:c.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(h||void 0)},s)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:c})=>this.params.output.liveTime$.next(l+c*1e3),s)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:c,quality:u,size:h,bandwidth:d,fps:f})=>({id:c,quality:u,size:h,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,s));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),lt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(r.isNullable(s))return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(s.url);if((a||n)&&s.id===this.masterManifest.id){const{max:u,min:h}=(t=(e=a==null?void 0:a.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[d,f]of[[u,"mq"],[h,"lq"]]){const p=String(parseFloat(d||""));f&&d&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ee.DASH_CMAF_OFFSET_P:ee.OFFSET_P,c=ge(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",c),this.video.load(),Gr(c).then(u=>{var h;if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const d=(h=this.params.source.maxSeekBackTime)!==null&&h!==void 0?h:this.maxSeekBackTime$.getValue();if(r.isNullable(d)||!isFinite(d))try{Yt(c).then(f=>f.text()).then(f=>{var p;const v=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(v){const m=new URL(v,c).toString();Gr(m).then(S=>{r.isNullable(S)||this.maxSeekBackTime$.next(S)})}})}catch(f){}}})}playIfAllowed(){ct(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.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 q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(q||(q={}));class Fm{constructor(e){this.subscription=new r.Subscription,this.videoState=new J(q.STOPPED),this.textTracksManager=new qe,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===exports.PlaybackState.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(s===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o||l||c){const d=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:f}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),h.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&h.state===I.Requested&&this.seek(h.position),s){case q.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case q.CHANGING_MANIFEST:break;default:return r.assertNever(s)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ea(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks: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:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,a;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(a=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=o.getState())===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:"master",h=this.manifests$.getValue();if(!h.length)return;const d=l?"master":u;return l&&!c&&o.startTransitionTo(this.masterManifest),h.find(f=>f.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=dt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Kt(this.video,t.isLooped,s)),this.subscription.add(ut(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},s).add(a.loadedMetadata$.subscribe(()=>{var l;const c=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),h=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(h&&r.isNonNullable(h.to)){const f=h.to.id;this.params.desiredState.videoTrack.setState(h.to);const p=this.manifests$.getValue().find(v=>v.id===f);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Le(p.url));const v=this.params.desiredState.playbackRate.getState(),m=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(v!==m){const S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(v),S.playbackRate=v)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from===q.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===I.Requested&&this.seek(c.position)},s))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:c,quality:u,size:h,bandwidth:d,fps:f})=>({id:c,quality:u,size:h,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,s)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(r.merge(r.fromEvent(l,"addtrack"),r.fromEvent(l,"removetrack"),r.fromEvent(l,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let c=0;c<l.length;c++)l[c].mode="hidden"},s))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),lt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(r.isNullable(s))return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(s.url);if((a||n)&&s.id===this.masterManifest.id){const{max:l,min:c}=(t=(e=a==null?void 0:a.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,h]of[[l,"mq"],[c,"lq"]]){const d=String(parseFloat(u||""));h&&u&&o.searchParams.set(h,d)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){ct(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(K||(K={}));class Um{constructor(e){this.subscription=new r.Subscription,this.videoState=new J(K.STOPPED),this.trackUrls={},this.textTracksManager=new qe,this.syncPlayback=()=>{var t,s,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),h=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.seekState.getState();if(u&&n!==K.READY&&!h){this.handleQualityLimitTransition(u.to.max);return}if(n===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(h){const{currentTime:f}=this.video;this.prepare(),d.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:f*1e3,forcePrecise:!0}),h.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((a=(s=this.trackUrls[h.to.id])===null||s===void 0?void 0:s.track)===null||a===void 0?void 0:a.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===I.Requested&&this.seek(d.position),n){case K.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},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=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=dt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Kt(this.video,t.isLooped,s)),this.subscription.add(ut(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),n(It(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l,c;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY);const u=this.params.desiredState.videoTrack.getTransition();if(u&&r.isNonNullable(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);const h=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())===null||c===void 0?void 0:c.playbackRate;if(h!==d){const f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(h),f.playbackRate=h)}}this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),lt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;r.assertNonNullable(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];r.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Zs(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Le(s))}playIfAllowed(){ct(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,a,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const c=(s=Object.values(this.trackUrls).find(d=>!r.isInvariantQuality(d.track.quality)&&r.isLowerOrEqual(d.track.quality,e)))===null||s===void 0?void 0:s.track,u=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,h=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(c&&h&&r.isHigherOrEqual(h.quality,c.quality)&&(o=c),!o){const d=Object.values(this.trackUrls).filter(p=>!r.isInvariantQuality(p.track.quality)&&r.isHigher(p.track.quality,e)),f=d.length;f&&(o=d[f-1].track)}o&&(l=o.quality)}else if(!e){const c=Object.values(this.trackUrls).map(u=>u.track);o=Ui(c,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.startTransitionTo(o)),this.params.output.autoVideoTrackLimits$.next({max:l})}}const Yr=["stun:videostun.mycdn.me:80"],jm=1e3,Hm=3,Ls=()=>null;class Gm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ls,this.externalStopCallback=Ls,this.externalErrorCallback=Ls,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:Yr}]};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:r.ErrorCategory.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),jm)}normalizeOptions(e={}){const t={stunServerList:Yr,maxRetryNumber:Hm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var G;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));class Ym{constructor(e){this.videoState=new J(G.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED){t!==G.STOPPED&&(this.videoState.startTransitionTo(G.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(G.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case G.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ot(e.container),this.liveStreamClient=new Gm(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),lt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=dt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,s));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(It(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===G.READY&&this.videoState.setState(G.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},s)).add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING)},s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ut(this.video,t.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case G.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case G.READY:break;case G.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case G.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},s)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(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(Le(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:r.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(G.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:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ct(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class qr{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 ne;(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"})(ne||(ne={}));var Ge;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Ge||(Ge={}));var Ds,xs,_s,Rs,pi,Is,mi,Ns,vi,Os,Si,Ms,bi,Bs,gi,Vs;const lo=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,Ye=document.createElement("video"),qm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',zm='video/mp4; codecs="hev1.1.6.L93.B0"',uo='video/webm; codecs="vp09.00.10.08"',co='video/webm; codecs="av01.0.00M.08"',Wm='audio/mp4; codecs="mp4a.40.2"',Qm='audio/webm; codecs="opus"',Ze={mms:no(),mse:Am(),hls:!!(!((Ds=Ye.canPlayType)===null||Ds===void 0)&&Ds.call(Ye,"application/x-mpegurl")||!((xs=Ye.canPlayType)===null||xs===void 0)&&xs.call(Ye,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},he={mp4:!!(!((_s=Ye.canPlayType)===null||_s===void 0)&&_s.call(Ye,"video/mp4")),webm:!!(!((Rs=Ye.canPlayType)===null||Rs===void 0)&&Rs.call(Ye,"video/webm")),cmaf:!0},Ce={h264:!!(!((Is=(pi=Xe())===null||pi===void 0?void 0:pi.isTypeSupported)===null||Is===void 0)&&Is.call(pi,qm)),h265:!!(!((Ns=(mi=Xe())===null||mi===void 0?void 0:mi.isTypeSupported)===null||Ns===void 0)&&Ns.call(mi,zm)),vp9:!!(!((Os=(vi=Xe())===null||vi===void 0?void 0:vi.isTypeSupported)===null||Os===void 0)&&Os.call(vi,uo)),av1:!!(!((Ms=(Si=Xe())===null||Si===void 0?void 0:Si.isTypeSupported)===null||Ms===void 0)&&Ms.call(Si,co)),aac:!!(!((Bs=(bi=Xe())===null||bi===void 0?void 0:bi.isTypeSupported)===null||Bs===void 0)&&Bs.call(bi,Wm)),opus:!!(!((Vs=(gi=Xe())===null||gi===void 0?void 0:gi.isTypeSupported)===null||Vs===void 0)&&Vs.call(gi,Qm))},Ut=(Ce.h264||Ce.h265)&&Ce.aac;let et;const Km=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:co}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:uo}})]);et={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Km()}catch(i){console.error(i)}const qt=Ze.hls&&he.mp4,Jm=()=>Object.keys(Ce).filter(i=>Ce[i]),Xm=(i,e=!1,t=!1)=>{const s=Ze.mse||Ze.mms&&t;return i.filter(a=>{switch(a){case exports.VideoFormat.DASH_SEP:return s&&he.mp4&&Ut;case exports.VideoFormat.DASH_WEBM:return s&&he.webm&&Ce.vp9&&Ce.opus;case exports.VideoFormat.DASH_WEBM_AV1:return s&&he.webm&&Ce.av1&&Ce.opus;case exports.VideoFormat.DASH_LIVE:return Ze.mse&&he.mp4&&Ut;case exports.VideoFormat.DASH_LIVE_CMAF:return s&&he.mp4&&Ut&&he.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return s&&he.mp4&&Ut;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&Ze.mse&&he.mp4&&Ut;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return he.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ze.webrtc&&Ze.ws&&Ce.h264&&(he.mp4||he.webm);default:return r.assertNever(a)}})},He=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case Ge.VP9:return[e,t];case Ge.AV1:return[t,e];case Ge.NONE:return[];case Ge.SMOOTH:return et?et[t].smooth?[t,e]:et[e].smooth?[e,t]:[t,e]:[e,t];case Ge.POWER_EFFICIENT:return et?et[t].powerEfficient?[t,e]:et[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(i)}return[e,t]},Zm=({webmCodec:i,androidPreferredFormat:e})=>{if(lo)switch(e){case ne.MPEG:return[exports.VideoFormat.MPEG,...He(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ne.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...He(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case ne.DASH:return[...He(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];case ne.DASH_ANY_MPEG:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,...He(i),exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ne.DASH_ANY_WEBM:return[...He(i),exports.VideoFormat.MPEG,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ne.DASH_SEP:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.MPEG,...He(i),exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];default:r.assertNever(e)}return qt?[...He(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...He(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},ev=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...s,...a],o=[...a,...s];let l;if(lo)switch(i){case ne.DASH:case ne.DASH_ANY_MPEG:case ne.DASH_ANY_WEBM:case ne.DASH_SEP:{l=n;break}case ne.HLS:case ne.MPEG:{l=o;break}default:r.assertNever(i)}else qt?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},zr=i=>i?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var tv=i=>new r.Observable(e=>{const t=new r.Subscription,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:h})=>`${u}-${h}`)),a=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,c="unknown";return t.add(s.subscribe(u=>{l&&window.clearTimeout(l),c=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),c="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(c),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const iv={chunkDuration:5e3,maxParallelRequests:5};class sv{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),currentVideoSegmentLength$:new r.ValueSubject(0),currentAudioSegmentLength$:new r.ValueSubject(0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),elementVisible$:new r.ValueSubject(!0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Xm([...ev(this.params.tuning),...Zm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:s,formatsToAvoid:a}=this.params.tuning;let n=[];s?n=[s]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new qr(n);const o=[...zr(!0),...zr(!1)];this.chromecastFormatsIterator=new qr(o.filter(l=>r.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}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(),a=s.state!==I.None;if(this.params.desiredState.seekState.setState({state:I.Requested,position:a?s.position:t,forcePrecise:a?s.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ae.SCREEN:return this.createScreenProvider(t);case ae.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:a}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return r.assertNonNullable(l),new Rm({...o,source:l,sourceHls:c})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Im({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),qt||!this.params.tuning.useHlsJs?new Fm({...o,source:l}):new Nm({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Vm({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Um({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Ff({...o,source:l,config:{...iv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Ym({container:s,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new ef({connection:l,meta:n,container:s,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ae.CHROMECAST:ae.SCREEN}chooseFormat(e){switch(e){case ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case ae.SCREEN:return this.screenFormatsIterator.next();case ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case ae.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return Pi(Object.entries(e).map(([a,n])=>[a,s(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,s=0;return e.add(r.merge(this.providerOutput.error$,tv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=a.category===r.ErrorCategory.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=s<this.params.tuning.providerErrorLimit&&!l;c&&!l&&(o&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(s++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:ae.SCREEN)}})),e}}const av=5e3,Wr="one_video_throughput",Qr="one_video_rtt",Ne=window.navigator.connection,Kr=()=>{const i=Ne==null?void 0:Ne.downlink;if(r.isNonNullable(i)&&i!==10)return i*1e3},Jr=()=>{const i=Ne==null?void 0:Ne.rtt;if(r.isNonNullable(i)&&i!==3e3)return i},Xr=(i,e,t)=>{const s=t*8,a=s/i;return s/(a+e)};class Ht{constructor(e){var t,s;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Ht.load(Wr)||(e.useBrowserEstimation?Kr():void 0)||av,n=(s=(t=Ht.load(Qr))!==null&&t!==void 0?t:e.useBrowserEstimation?Jr():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Xr(a,n,e.rttPenaltyRequestSize)),this.throughput=ea.getSmoothedValue(a,-1,e),this.rtt=ea.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const c=Kr();c&&this.throughput.next(c);const u=Jr();r.isNonNullable(u)&&this.rtt.next(u)};Ne&&"onchange"in Ne&&this.subscription.add(r.fromEvent(Ne,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(Wr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Qr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Xr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,s=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),c=o-t,u=l-s;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let a=0,n=r.now(),o=0,l=r.now();const c=h=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},u=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(a,r.now()-n,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(r.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=d.byteLength;else{const p=l-n;p&&this.addRawSpeed(o,p,1,t),o=d.byteLength,n=r.now()}l=r.now()}else a+=d.byteLength,o+=d.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-l,this.concurrentDownloads.size),o=0,l=r.now());await(s==null?void 0:s.read().then(u,c))}};this.concurrentDownloads.add(e),s==null||s.read().then(u,c)}addRawSpeed(e,t,s=1,a=!1){if(Ht.sanityCheck(e,t,a)){const n=e*8/t;this.throughput.next(n*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=r.safeStorage.get(e);if(r.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Zr={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:r.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Ge.VP9,androidPreferredFormat:ne.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}},rv=i=>{var e;return{...r.fillWithDefault(i,Zr),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Zr.configName]}};var en=({seekState:i,position$:e})=>r.merge(i.stateChangeEnded$.pipe(r.map(({to:t})=>{var s;return t.state===I.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>i.getState().state===I.None))),nv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return r.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const ov=(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(r.filter(a=>a.length>0),r.once()).subscribe(a=>{a.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class lv{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.hasLiveOffsetByPaused=new r.ValueSubject(!1),this.hasLiveOffsetByPausedTimer=0,this.desiredState={playbackState:new J(exports.PlaybackState.STOPPED),seekState:new J({state:I.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),internalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({}),cameraOrientation:new J({x:0,y:0})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1),currentVideoSegmentLength$:new r.ValueSubject(0),currentAudioSegmentLength$:new r.ValueSubject(0)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:Ef},this.initLogs(),this.tuning=rv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ht(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,a)=>{const n=Reflect.get(t,s,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const c=o.map(d=>JSON.stringify(d,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(s)}`,h=`Exception calling ${u} (${c.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:h,thrown:l}),l}}}})}initVideo(e){var t,s,a;return this.config=e,this.domContainer=nv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new sv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?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===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ks()?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=s&&!a&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:I.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(r.filter(s=>s.length>0),r.once()).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;r.assertNonNullable(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 ov(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 a=s.getCameraRotation(),n=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===I.None?void 0:t.position;return r.isNonNullable(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:a})=>s||a||0,0),height:e.reduce((s,{height:a})=>s||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===I.Requested?this.desiredState.seekState.setState({...o,state:I.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===I.Applying&&(this.desiredState.seekState.setState({state:I.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,c)=>r.isInvariantQuality(l)?1:r.isInvariantQuality(c)?-1:r.isHigher(c,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const c of o)c.fps&&(l[c.quality]=c.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({hasLiveOffsetByPaused:r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(o=>o.to),r.filterChanged(),r.map(o=>o===exports.PlaybackState.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:o,isLowLatency:l})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),o){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(l));return}this.hasLiveOffsetByPaused.next(!1)})).add(r.combine({atLiveEdge:r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:en({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:l,isLowLatency:c})=>{const u=this.getActiveLiveDelay(c);return o&&Math.abs(l)<u/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(r.map(({atLiveEdge:o,hasPausedTimeoutCase:l})=>o&&!l)).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:l,duration:c})=>o&&(Math.abs(c)-Math.abs(l))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(en({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>s.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,s).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||s.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,c;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(c=o==null?void 0:o.size)===null||c===void 0?void 0:c.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue();let d;h===exports.ChromecastState.CONNECTED?d=exports.Surface.SECOND_SCREEN:c?u?o?d=exports.Surface.PIP:l?d=exports.Surface.FULLSCREEN:d=exports.Surface.INLINE:d=exports.Surface.INVISIBLE:d=exports.Surface.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(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((s,a)=>s.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const a=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;a&&(s=e.find(({quality:n})=>n===a),s||this.setAutoQuality(!0)),s||(s=Ui(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),Tf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>yf(s)),this.providerContainer.current$.subscribe(({type:s})=>hi("provider",s)),t.duration$.subscribe(s=>hi("duration",s)),t.availableVideoTracks$.pipe(r.filter(s=>!!s.length),r.once()).subscribe(s=>hi("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(r.map(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)),hi("codecs",Jm())}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(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);a&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(a=>a.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 uv=`@vkontakte/videoplayer-core@${tn}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=lv;exports.SDK_VERSION=uv;exports.VERSION=tn;
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 ls=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 os(this.params.fov,this.params.orientation),this.cameraRotationManager=new us(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(dm,this.gl.VERTEX_SHADER),r=this.createShader(pm,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 Jt=class{constructor(e){this.subscription=new C.Subscription;this.videoState=new H("stopped");this.elementSize$=new C.ValueSubject(void 0);this.textTracksManager=new De;this.droppedFramesManager=new Ja;this.videoTracks$=new C.ValueSubject([]);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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(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"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,C.assertNever)(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new ls(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=ye(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(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ns({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=Ee(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:C.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,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((0,C.map)(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((0,C.filter)(C.isNonNullable),(0,C.once)()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,C.observeElementSize)(this.video),this.elementSize$),s(Me(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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();(0,C.assertNonNullable)(p,"Manifest not loaded or empty");let m=Array.from(p.audio).sort((y,v)=>v.bitrate-y.bitrate),f=Array.from(p.video).sort((y,v)=>v.bitrate-y.bitrate),g=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let y of m){let v=em(y);v&&this.audioTracks.push({track:v,representation:y})}for(let y of f){let v=Zf(y);if(v){d.push({track:v,representation:y});let w=!this.params.tuning.isAudioDisabled&&tm(m,f,y);w&&this.audioRepresentations.set(y.id,w)}}this.videoTracks$.next(d);for(let y of g){let v=rm(y);v&&this.textTracks.push({track:v,representation:y})}this.params.output.availableVideoTracks$.next(d.map(({track:y})=>y)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:y})=>y)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:y})=>y));let S=this.selectVideoRepresentation();(0,C.assertNonNullable)(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))==null?void 0:c.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:C.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,C.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,C.fromEvent)(this.video,"progress")).subscribe(()=>{let 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 m=this.params.desiredState.autoVideoTrackSwitching.getState(),f=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let g=d.id;!this.params.output.elementVisible$.getValue()&&m&&(g=this.videoTracks$.getValue().map(y=>y.representation).sort((y,v)=>v.bitrate-y.bitrate).filter(y=>{let v=(0,C.videoSizeToQuality)(y),w=(0,C.videoSizeToQuality)(d);if(v&&w)return(0,C.isLowerOrEqual)(v,w)&&(0,C.isLowerOrEqual)(v,f)}).map(y=>y.id)[0]),this.player.switchRepresentation("video",g).catch(n);let S=this.audioRepresentations.get(d.id);S&&this.player.switchRepresentation("audio",S.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to: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((0,C.filterChanged)(),(0,C.map)(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((0,C.map)(({to:u})=>u==="ready"),(0,C.filterChanged)());this.subscription.add((0,C.merge)(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((0,C.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,C.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,C.observableFrom)(["init"])).pipe((0,C.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,m,f,g,S,y;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:v}})=>v===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=kt(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&&(f=(m=this.audioRepresentations.get(r.id))==null?void 0:m.bitrate)!=null?f:0,a&&(S=(g=this.audioRepresentations.get(a.id))==null?void 0:g.bitrate)!=null?S:0),u=wt(this.videoTracks$.getValue().map(({track:v})=>v),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve: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&&((y=this.videoTracks$.getValue().find(({track:v})=>v===c))==null?void 0:y.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Te(this.video)}};var Bi=class extends Jt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Xt=require("@vkontakte/videoplayer-shared");var Vi=class extends Jt{constructor(e){super(e),this.liveOffset=new nt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Xt.combine)({interval:(0,Xt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,Xt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Xt.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var hm=Ne(Ya(),1);var q=require("@vkontakte/videoplayer-shared"),Ye={};var Ar=(i,e)=>new q.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),_i=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("initializing");this.textTracksManager=new De;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,q.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,q.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,q.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,q.assertNever)(e)}break;default:(0,q.assertNever)(t)}};this.video=ye(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(le(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),Te(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:q.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,hm.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,q.assertNonNullable)(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,q.assertNonNullable)(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:q.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Ee(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(Je(this.video,e.isLooped,r)),this.subscription.add(Ie(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,a.playbackRateState$,r)),s(Me(this.video),t.elementVisible$),this.subscription.add(Ar(this.hls,Ye.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:q.ErrorCategory.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"),P(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(Ar(this.hls,Ye.Events.MANIFEST_PARSED).pipe((0,q.map)(({levels:u})=>u.reduce((c,d)=>{var v,w;let p=d.name||d.height.toString(10),{width:m,height:f}=d,g=(w=Pt((v=d.attrs.QUALITY)!=null?v:""))!=null?w:(0,q.videoSizeToQuality)({width:m,height:f});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:f},fps:S};return this.trackLevels.set(p,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),s(Ar(this.hls,Ye.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,m=d.attrs.URI||"",f=d.lang,g="internal";c.push({id:p,url:m,language:f,type:g})}e.internalTextTracks.startTransitionTo(c)}}),s(Ar(this.hls,Ye.Events.LEVEL_LOADING).pipe((0,q.map)(({url:u})=>le(u))),t.hostname$),s(Ar(this.hls,Ye.Events.FRAG_CHANGED),u=>{var p,m,f,g;let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(xt(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=Ar(this.hls,Ye.Events.LEVEL_SWITCHED).pipe((0,q.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,q.filter)(q.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{var f;if((0,q.isNullable)(u))return;let c=(f=this.trackLevels.get(u.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,m=this.hls.levels[p];!m||c.bitrate>m.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=(0,q.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(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 xe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),P(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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var fm="X-Playback-Duration",Ho=async i=>{var a;let e=await lt(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(fm)?parseInt(e.headers.get(fm),10):void 0};var N=require("@vkontakte/videoplayer-shared");var Go=Ne(Ma(),1);var cs=require("@vkontakte/videoplayer-shared");var rP=i=>{let e=null;if(i.QUALITY&&(e=Pt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,cs.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},iP=(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,Go.default)(u[1].split(",").map(v=>v.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,m=rP(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[v,w]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));v&&w&&(S={width:v,height:w})}let y=new URL(t[++o],e).toString();m&&r.push({id:p,quality:m,url:y,bandwidth:f,size:S,fps:g})}if(c){let d=(0,Go.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),m=d.LANGUAGE,f=d.NAME;p&&m&&a.push({type:"internal",id:m,label:f,language:m,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},aP=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),jo=0,mm=async(i,e=i,t)=>{let a=await(await lt(i)).text();jo+=1;try{let{qualityManifests:s,textTracks:n}=iP(a,e);return{qualityManifests:s,textTracks:n}}catch(s){if(jo<=t.manifestRetryMaxCount)return await aP((0,cs.getExponentialDelay)(jo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),mm(i,e,t)}return{qualityManifests:[],textTracks:[]}},ds=mm;var Ni=class{constructor(e){this.subscription=new N.Subscription;this.videoState=new H("stopped");this.textTracksManager=new De;this.manifests$=new N.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new N.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,N.assertNever)(t)}};var t;this.params=e,this.video=ye(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:N.VideoQuality.INVARIANT,url:this.params.source.url},ds(pe(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:N.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:N.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.maxSeekBackTime$=new N.ValueSubject((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:N.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Ee(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(Ie(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,N.filterChanged)(),(0,N.map)(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&&(0,N.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(m=>m.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(le(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((0,N.combine)({startTime:this.manifestStartTime$.pipe((0,N.filter)(N.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe((0,N.map)(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=(0,N.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,N.observableFrom)(["init"])).pipe((0,N.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var o,l;let e=this.selectManifest();if((0,N.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max: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 m=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=pe(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Ho(n).then(u=>{var c;if(!(0,N.isNullable)(u))this.maxSeekBackTime$.next(u);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,N.isNullable)(d)||!isFinite(d))try{lt(n).then(p=>p.text()).then(p=>{var f;let m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(m){let g=new URL(m,n).toString();Ho(g).then(S=>{(0,N.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:N.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var Y=require("@vkontakte/videoplayer-shared");var Fi=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new H("stopped");this.textTracksManager=new De;this.manifests$=new Y.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,Y.assertNever)(t)}};this.params=e,this.video=ye(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Y.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ds(pe(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:Y.ErrorCategory.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:Y.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Ee(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(Je(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&(0,Y.isNonNullable)(u.to)){let p=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let m=this.manifests$.getValue().find(f=>f.id===p);if(m){this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(le(m.url));let f=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(f),S.playbackRate=f)}}}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((0,Y.map)(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)),!(0,Y.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,Y.merge)((0,Y.fromEvent)(o,"addtrack"),(0,Y.fromEvent)(o,"removetrack"),(0,Y.fromEvent)(o,"change"),(0,Y.observableFrom)(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=(0,Y.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,Y.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min: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(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var qi=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new De;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=ye(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:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Ee(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(Je(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,a.playbackRateState$,r)),s(Me(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&(0,J.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(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=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Te(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Di(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(le(t))}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let l=(s=Object.values(this.trackUrls).find(d=>!(0,J.isInvariantQuality)(d.track.quality)&&(0,J.isLowerOrEqual)(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&&(0,J.isHigherOrEqual)(c.quality,l.quality)&&(t=l),!t){let d=Object.values(this.trackUrls).filter(m=>!(0,J.isInvariantQuality)(m.track.quality)&&(0,J.isHigher)(m.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=wt(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})}};var ee=require("@vkontakte/videoplayer-shared");var gm=require("@vkontakte/videoplayer-shared"),bm=["stun:videostun.mycdn.me:80"],sP=1e3,nP=3,Yo=()=>null,ps=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=Yo;this.externalStopCallback=Yo;this.externalErrorCallback=Yo;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:bm}]};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:gm.ErrorCategory.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),sP)}normalizeOptions(e={}){let t={stunServerList:bm,maxRetryNumber:nP,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 H("stopped");this.maxSeekBackTime$=new ee.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,ee.assertNever)(e)}};this.subscription=new ee.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container),this.liveStreamClient=new ps(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ee.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ee.merge)(this.videoState.stateChangeStarted$.pipe((0,ee.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ee.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Ee(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(Me(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(Ie(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ee.assertNever)(n.to)}},r)).add((0,ee.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(le(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:ee.VideoQuality.INVARIANT}),this.video.srcObject=e,P(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:ee.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ee.ErrorCategory.DOM,thrown:e}))}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}};var I=require("@vkontakte/videoplayer-shared");var ht=require("@vkontakte/videoplayer-shared"),Am=(0,ht.getCurrentBrowser)().device===ht.CurrentClientDevice.Android,Ve=document.createElement("video"),lP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',cP='video/mp4; codecs="hev1.1.6.L93.B0"',Rm='video/webm; codecs="vp09.00.10.08"',Lm='video/webm; codecs="av01.0.00M.08"',dP='audio/mp4; codecs="mp4a.40.2"',pP='audio/webm; codecs="opus"',vm,Sm,Zt={mms:ss(),mse:om(),hls:!!((vm=Ve.canPlayType)!=null&&vm.call(Ve,"application/x-mpegurl")||(Sm=Ve.canPlayType)!=null&&Sm.call(Ve,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ym,Tm,Be={mp4:!!((ym=Ve.canPlayType)!=null&&ym.call(Ve,"video/mp4")),webm:!!((Tm=Ve.canPlayType)!=null&&Tm.call(Ve,"video/webm")),cmaf:!0},hs,Im,fs,Em,ms,xm,bs,Pm,gs,wm,vs,km,Ze={h264:!!((Im=(hs=pt())==null?void 0:hs.isTypeSupported)!=null&&Im.call(hs,lP)),h265:!!((Em=(fs=pt())==null?void 0:fs.isTypeSupported)!=null&&Em.call(fs,cP)),vp9:!!((xm=(ms=pt())==null?void 0:ms.isTypeSupported)!=null&&xm.call(ms,Rm)),av1:!!((Pm=(bs=pt())==null?void 0:bs.isTypeSupported)!=null&&Pm.call(bs,Lm)),aac:!!((wm=(gs=pt())==null?void 0:gs.isTypeSupported)!=null&&wm.call(gs,dP)),opus:!!((km=(vs=pt())==null?void 0:vs.isTypeSupported)!=null&&km.call(vs,pP))},ji=(Ze.h264||Ze.h265)&&Ze.aac,er,hP=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:Lm}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Rm}})]);er={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{hP()}catch(i){console.error(i)}var Rr=Zt.hls&&Be.mp4,$m=()=>Object.keys(Ze).filter(i=>Ze[i]),Cm=(i,e=!1,t=!1)=>{let r=Zt.mse||Zt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Be.mp4&&ji;case"DASH_WEBM":return r&&Be.webm&&Ze.vp9&&Ze.opus;case"DASH_WEBM_AV1":return r&&Be.webm&&Ze.av1&&Ze.opus;case"DASH_LIVE":return Zt.mse&&Be.mp4&&ji;case"DASH_LIVE_CMAF":return r&&Be.mp4&&ji&&Be.cmaf;case"DASH_ONDEMAND":return r&&Be.mp4&&ji;case"HLS":case"HLS_ONDEMAND":return Rr||e&&Zt.mse&&Be.mp4&&ji;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Rr;case"MPEG":return Be.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Zt.webrtc&&Zt.ws&&Ze.h264&&(Be.mp4||Be.webm);default:return(0,ht.assertNever)(a)}})},Rt=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 er?er[t].smooth?[t,e]:er[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return er?er[t].powerEfficient?[t,e]:er[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ht.assertNever)(i)}return[e,t]},Dm=({webmCodec:i,androidPreferredFormat:e})=>{if(Am)switch(e){case"mpeg":return["MPEG",...Rt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...Rt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...Rt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...Rt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Rt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Rt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,ht.assertNever)(e)}return Rr?[...Rt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...Rt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Mm=({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(Am)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,ht.assertNever)(i)}else Rr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Wo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var ft=require("@vkontakte/videoplayer-shared"),Om=i=>new ft.Observable(e=>{let t=new ft.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,ft.map)(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,ft.map)(({type:u})=>u!==void 0)),n=new ft.Subject,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 fP={chunkDuration:5e3,maxParallelRequests:5},Gi=class{constructor(e){this.current$=new I.ValueSubject({type:void 0});this.providerError$=new I.Subject;this.noAvailableProvidersError$=new I.Subject;this.providerOutput={position$:new I.ValueSubject(0),duration$:new I.ValueSubject(1/0),volume$:new I.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new I.ValueSubject(void 0),currentVideoSegmentLength$:new I.ValueSubject(0),currentAudioSegmentLength$:new I.ValueSubject(0),availableVideoTracks$:new I.ValueSubject([]),availableAudioTracks$:new I.ValueSubject([]),isAudioAvailable$:new I.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new I.ValueSubject(!1),autoVideoTrackLimits$:new I.ValueSubject(void 0),currentBuffer$:new I.ValueSubject(void 0),isBuffering$:new I.ValueSubject(!0),error$:new I.Subject,warning$:new I.Subject,willSeekEvent$:new I.Subject,seekedEvent$:new I.Subject,loopedEvent$:new I.Subject,endedEvent$:new I.Subject,firstBytesEvent$:new I.Subject,firstFrameEvent$:new I.Subject,canplay$:new I.Subject,isLive$:new I.ValueSubject(void 0),isLowLatency$:new I.ValueSubject(!1),canChangePlaybackSpeed$:new I.ValueSubject(!0),liveTime$:new I.ValueSubject(void 0),liveBufferTime$:new I.ValueSubject(void 0),availableTextTracks$:new I.ValueSubject([]),currentTextTrack$:new I.ValueSubject(void 0),hostname$:new I.ValueSubject(void 0),httpConnectionType$:new I.ValueSubject(void 0),httpConnectionReused$:new I.ValueSubject(void 0),inPiP$:new I.ValueSubject(!1),inFullscreen$:new I.ValueSubject(!1),element$:new I.ValueSubject(void 0),elementVisible$:new I.ValueSubject(!0),availableSources$:new I.ValueSubject(void 0),is3DVideo$:new I.ValueSubject(!1)};this.subscription=new I.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Cm([...Mm(this.params.tuning),...Dm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,I.isNonNullable)(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Hi(s);let n=[...Wo(!0),...Wo(!1)];this.chromecastFormatsIterator=new Hi(n.filter(o=>(0,I.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,I.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:I.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,I.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,I.assertNonNullable)(o),new Bi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Vi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),Rr||!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(0,I.assertNonNullable)(o),new Ni({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new qi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new cf({...n,source:o,config:{...fP,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(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(0,I.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,I.assertNonNullable)(o),new ei({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,I.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,I.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,I.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Bm.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new I.Subscription,t=!1,r=0;return e.add((0,I.merge)(this.providerOutput.error$,Om({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,I.map)(a=>({id:`ProviderHangup:${a}`,category:I.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,I.filter)(({to:s})=>s==="playing"),(0,I.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===I.ErrorCategory.NETWORK,o=a.category===I.ErrorCategory.FATAL,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}};var D=require("@vkontakte/videoplayer-shared");var mP=5e3,Vm="one_video_throughput",_m="one_video_rtt",mt=window.navigator.connection,Nm=()=>{let i=mt==null?void 0:mt.downlink;if((0,D.isNonNullable)(i)&&i!==10)return i*1e3},Fm=()=>{let i=mt==null?void 0:mt.rtt;if((0,D.isNonNullable)(i)&&i!==3e3)return i},qm=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Qo=class i{constructor(e){this.subscription=new D.Subscription;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(Vm)||(e.useBrowserEstimation?Nm():void 0)||mP,r=(s=(a=i.load(_m))!=null?a:e.useBrowserEstimation?Fm():void 0)!=null?s:0;if(this.throughput$=new D.ValueSubject(t),this.rtt$=new D.ValueSubject(r),this.rttAdjustedThroughput$=new D.ValueSubject(qm(t,r,e.rttPenaltyRequestSize)),this.throughput=zt.getSmoothedValue(t,-1,e),this.rtt=zt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let l=Nm();l&&this.throughput.next(l);let u=Fm();(0,D.isNonNullable)(u)&&this.rtt.next(u)};mt&&"onchange"in mt&&this.subscription.add((0,D.fromEvent)(mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{D.safeStorage.set(Vm,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{D.safeStorage.set(_m,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,D.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,D.map)(({throughput:n,rtt:o})=>qm(n,o,e.rttPenaltyRequestSize)),(0,D.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,D.now)(),a=new D.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,D.fromEvent)(e,"progress").pipe((0,D.once)()).subscribe(s=>{t=s.loaded,r=(0,D.now)()}));break;case 1:case 0:a.add((0,D.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,D.now)()}));break}a.add((0,D.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,D.now)(),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=(0,D.now)(),n=0,o=(0,D.now)(),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,(0,D.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if((0,D.now)()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,D.now)()}o=(0,D.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,D.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,D.now)()-o,this.concurrentDownloads.size),n=0,o=(0,D.now)());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=D.safeStorage.get(e);if((0,D.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},Um=Qo;var Yi=require("@vkontakte/videoplayer-shared"),Hm={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:Yi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Yi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},jm=i=>{var e;return{...(0,Yi.fillWithDefault)(i,Hm),configName:[...(e=i.configName)!=null?e:[],...Hm.configName]}};var h=require("@vkontakte/videoplayer-shared");var bt=require("@vkontakte/videoplayer-shared"),zo=({seekState:i,position$:e})=>(0,bt.merge)(i.stateChangeEnded$.pipe((0,bt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,bt.filter)(bt.isNonNullable)),e.pipe((0,bt.filter)(()=>i.getState().state==="none")));var Gm=require("@vkontakte/videoplayer-shared"),Ym=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,Gm.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var Ss=require("@vkontakte/videoplayer-shared"),Wm=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Ss.filter)(a=>a.length>0),(0,Ss.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Wi=class{constructor(e={configName:[]}){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new h.ValueSubject("stopped"),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,firstBytes$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),dumpTelemetry:nf};if(this.initLogs(),this.tuning=jm(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new sa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Um(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,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:h.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=Ym(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Gi({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&&!ni()?(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,h.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Wm(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,h.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,h.isInvariantQuality)(o)?1:(0,h.isInvariantQuality)(l)?-1:(0,h.isHigher)(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((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,h.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:zo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(zo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,h.once)(),(0,h.map)(n=>n!=null?n:(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,h.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,h.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var 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((0,h.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),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((0,h.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(r=>r.length>0),(0,h.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=wt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),sf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>af(r)),this.providerContainer.current$.subscribe(({type:r})=>ri("provider",r)),e.duration$.subscribe(r=>ri("duration",r)),e.availableVideoTracks$.pipe((0,h.filter)(r=>!!r.length),(0,h.once)()).subscribe(r=>ri("tracks",r)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe((0,h.map)(r=>r==null?void 0:r.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(r=>this.subscription.add(r)),ri("codecs",$m())}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:h.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var et=require("@vkontakte/videoplayer-shared"),bP=`@vkontakte/videoplayer-core@${Ls}`;