@vkontakte/videoplayer-core 2.0.135-dev.f94adb28.0 → 2.0.136-beta.0

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 (113) hide show
  1. package/es2015.cjs.js +46 -53
  2. package/es2015.esm.js +42 -49
  3. package/es2018.cjs.js +54 -61
  4. package/es2018.esm.js +54 -61
  5. package/es2024.cjs.js +53 -60
  6. package/es2024.esm.js +51 -58
  7. package/esnext.cjs.js +53 -60
  8. package/esnext.esm.js +51 -58
  9. package/evergreen.esm.js +39 -46
  10. package/package.json +2 -2
  11. package/types/providers/DashProvider/baseDashProvider.d.ts +2 -1
  12. package/types/providers/DashProvider/lib/LiveTextManager.d.ts +1 -1
  13. package/types/providers/DashProvider/lib/buffer.d.ts +2 -1
  14. package/types/providers/DashProvider/lib/fetcher.d.ts +2 -1
  15. package/types/providers/DashProvider/lib/player.d.ts +6 -1
  16. package/types/providers/DashProvider/lib/types.d.ts +2 -159
  17. package/types/providers/DashProvider/lib/utils.d.ts +1 -2
  18. package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -1
  19. package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +1 -1
  20. package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -1
  21. package/types/providers/DashProviderNew/lib/fetcher.d.ts +2 -1
  22. package/types/providers/DashProviderNew/lib/player.d.ts +6 -1
  23. package/types/providers/DashProviderNew/lib/types.d.ts +2 -159
  24. package/types/providers/DashProviderNew/lib/utils.d.ts +1 -2
  25. package/types/providers/utils/error.d.ts +1 -0
  26. package/types/providers/{DashProvider/lib → utils}/parsers/index.d.ts +1 -1
  27. package/types/providers/{DashProviderNew/lib → utils}/parsers/mpd.d.ts +1 -1
  28. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxModel.d.ts +4 -4
  29. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxParser.d.ts +2 -2
  30. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/box.d.ts +8 -8
  31. package/types/providers/utils/parsers/mpeg/boxes/avc1.d.ts +8 -0
  32. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/equi.d.ts +2 -2
  33. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/ftyp.d.ts +2 -2
  34. package/types/providers/utils/parsers/mpeg/boxes/index.d.ts +26 -0
  35. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mdat.d.ts +2 -2
  36. package/types/providers/utils/parsers/mpeg/boxes/mdia.d.ts +8 -0
  37. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mfhd.d.ts +2 -2
  38. package/types/providers/utils/parsers/mpeg/boxes/minf.d.ts +8 -0
  39. package/types/providers/utils/parsers/mpeg/boxes/moof.d.ts +8 -0
  40. package/types/providers/utils/parsers/mpeg/boxes/moov.d.ts +8 -0
  41. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/mvhd.d.ts +2 -2
  42. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/prhd.d.ts +2 -2
  43. package/types/providers/utils/parsers/mpeg/boxes/proj.d.ts +8 -0
  44. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/sidx.d.ts +2 -2
  45. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/st3d.d.ts +2 -2
  46. package/types/providers/utils/parsers/mpeg/boxes/stbl.d.ts +8 -0
  47. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/stsd.d.ts +2 -2
  48. package/types/providers/utils/parsers/mpeg/boxes/sv3d.d.ts +8 -0
  49. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfdt.d.ts +2 -2
  50. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tfhd.d.ts +2 -2
  51. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/tkhd.d.ts +2 -2
  52. package/types/providers/utils/parsers/mpeg/boxes/traf.d.ts +8 -0
  53. package/types/providers/utils/parsers/mpeg/boxes/trak.d.ts +8 -0
  54. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/trun.d.ts +2 -2
  55. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/boxes/unknown.d.ts +1 -1
  56. package/types/providers/utils/parsers/mpeg/boxes/uuid.d.ts +18 -0
  57. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/fullBox.d.ts +2 -2
  58. package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/isobmff.d.ts +1 -1
  59. package/types/providers/utils/parsers/types.d.ts +159 -0
  60. package/types/providers/{DashProvider/lib → utils}/parsers/webm/webm.d.ts +1 -1
  61. package/types/utils/tuningConfig.d.ts +2 -4
  62. package/types/providers/DashProvider/lib/parsers/mpd.d.ts +0 -3
  63. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
  64. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +0 -26
  65. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
  66. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
  67. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
  68. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
  69. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
  70. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
  71. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
  72. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
  73. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
  74. package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
  75. package/types/providers/DashProviderNew/lib/parsers/ietf/index.d.ts +0 -13
  76. package/types/providers/DashProviderNew/lib/parsers/index.d.ts +0 -3
  77. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxModel.d.ts +0 -20
  78. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxParser.d.ts +0 -21
  79. package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxTypeEnum.d.ts +0 -30
  80. package/types/providers/DashProviderNew/lib/parsers/mpeg/box.d.ts +0 -74
  81. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/avc1.d.ts +0 -8
  82. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/equi.d.ts +0 -21
  83. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/ftyp.d.ts +0 -17
  84. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/index.d.ts +0 -26
  85. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdat.d.ts +0 -15
  86. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdia.d.ts +0 -8
  87. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mfhd.d.ts +0 -11
  88. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/minf.d.ts +0 -8
  89. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moof.d.ts +0 -8
  90. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moov.d.ts +0 -8
  91. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mvhd.d.ts +0 -35
  92. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/prhd.d.ts +0 -16
  93. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/proj.d.ts +0 -8
  94. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sidx.d.ts +0 -48
  95. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/st3d.d.ts +0 -23
  96. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stbl.d.ts +0 -8
  97. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stsd.d.ts +0 -11
  98. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sv3d.d.ts +0 -8
  99. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfdt.d.ts +0 -17
  100. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfhd.d.ts +0 -22
  101. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tkhd.d.ts +0 -42
  102. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/traf.d.ts +0 -8
  103. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trak.d.ts +0 -8
  104. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trun.d.ts +0 -31
  105. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/unknown.d.ts +0 -6
  106. package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/uuid.d.ts +0 -11
  107. package/types/providers/DashProviderNew/lib/parsers/mpeg/fullBox.d.ts +0 -15
  108. package/types/providers/DashProviderNew/lib/parsers/mpeg/isobmff.d.ts +0 -12
  109. package/types/providers/DashProviderNew/lib/parsers/webm/ebml.d.ts +0 -76
  110. package/types/providers/DashProviderNew/lib/parsers/webm/webm.d.ts +0 -3
  111. /package/types/providers/{DashProvider/lib → utils}/parsers/ietf/index.d.ts +0 -0
  112. /package/types/providers/{DashProvider/lib → utils}/parsers/mpeg/BoxTypeEnum.d.ts +0 -0
  113. /package/types/providers/{DashProvider/lib → utils}/parsers/webm/ebml.d.ts +0 -0
package/evergreen.esm.js CHANGED
@@ -1,77 +1,77 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.135-dev.f94adb28.0
3
- * Tue, 01 Jul 2025 09:29:11 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-135/doc/
2
+ * @vkontakte/videoplayer-core v2.0.136-beta.0
3
+ * Fri, 11 Jul 2025 16:07:23 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
5
5
  */
6
- var Oo="2.0.135-dev.f94adb28.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),Et=(v=>(v.MPEG="MPEG",v.DASH="DASH",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_STREAMS="DASH_STREAMS",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))(Et||{});var As=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(As||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(rn||{}),Ps=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ps||{});import{assertNever as jo,assertNonNullable as qc,isNonNullable as Ms,ValueSubject as sn,Subject as Gc,Subscription as Yc,merge as Kc,observableFrom as Xc,fromEvent as _o,map as No,tap as Uo,filterChanged as Jc,isNullable as an,ErrorCategory as Ho}from"@vkontakte/videoplayer-shared/evergreen";var Fo=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ls=class{constructor(e){this.connection$=new sn(void 0);this.castState$=new sn("NOT_AVAILABLE");this.errorEvent$=new Gc;this.realCastState$=new sn("NOT_AVAILABLE");this.subscription=new Yc;this.isDestroyed=!1;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 i=Ms(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Fo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ho.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();an(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();an(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(_o(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return jo(r.sessionState)}})).add(Kc(_o(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Uo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),No(r=>r.castState)),Xc([i.getCastState()])).pipe(Jc(),No(Zc),Uo(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Ms(this.connection$.getValue());if(s&&!a){let o=i.getCurrentSession();qc(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(an(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ms(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Ho.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Zc=n=>{switch(n){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 jo(n)}};import{assertNever as zo}from"@vkontakte/videoplayer-shared/evergreen";var pe=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:zo(t)}return n},Ct=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:zo(e)}};var P=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as ed,Subject as Bs,merge as Qo}from"@vkontakte/videoplayer-shared/evergreen";var _=class{constructor(e){this.transitionStarted$=new Bs;this.transitionEnded$=new Bs;this.transitionUpdated$=new Bs;this.forceChanged$=new Bs;this.stateChangeStarted$=Qo(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Qo(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||ed(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as td}from"@vkontakte/videoplayer-shared/evergreen";var Wo=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":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 td(n)}};import{assertNever as pi,assertNonNullable as Xt,debounce as qo,ErrorCategory as Go,fromEvent as Jt,isNonNullable as Yo,map as Ko,merge as Xo,observableFrom as id,Subject as rd,Subscription as nn,timeout as sd,getHighestQuality as ad}from"@vkontakte/videoplayer-shared/evergreen";var nd=5,od=5,ud=500,Jo=7e3,_i=class{constructor(e){this.subscription=new nn;this.loadMediaTimeoutSubscription=new nn;this.videoState=new _("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:pi(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:pi(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:pi(e)}break}default:pi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wo(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 nn;this.subscription.add(e),this.subscription.add(Xo(this.videoState.stateChangeStarted$.pipe(Ko(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ko(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new rd;e.add(r.pipe(qo(ud)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let o=a.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>nd)&&r.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,o=this.params.output.isBuffering$.getValue(),u=a===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<od&&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:pi(a)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Xo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,id(["init"])).pipe(qo(0));t(i,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 i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];Xt(l);let p=ad(Object.keys(l));Xt(p);let c=l[p];Xt(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Xt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Xt(l),i=pe(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Go.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return pi(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Yo(o)&&(a.metadata.title=o),Yo(u)&&(a.metadata.subtitle=u),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(sd(Jo).subscribe(()=>s(`timeout(${Jo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Go.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as eu}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as ld}from"@vkontakte/videoplayer-shared/evergreen";var Zo=n=>{try{n.pause(),n.playbackRate=0,ld(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as cd,Subscription as dd}from"@vkontakte/videoplayer-shared/evergreen";var on=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)}},un=window.WeakMap?new WeakMap:new on,ln=window.WeakMap?new WeakMap:new Map,pd=(n,e=20)=>{let t=0;return cd(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},Oe=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?eu(i):(i=document.createElement("video"),n.appendChild(i)),un.set(i,r);let s=new dd;return s.add(pd(i,e)),ln.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Fe=n=>{ln.get(n)?.unsubscribe(),ln.delete(n);let t=un.get(n);un.delete(n),t?eu(n):Zo(n)};import{assertNonNullable as Ui,isNonNullable as pt,isNullable as fd,fromEvent as hi,merge as tu,observableFrom as iu,filterChanged as ru,map as Hi,Subject as su,Subscription as bd,ValueSubject as gd,ErrorCategory as Sd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as cn,isNullable as hd,Subscription as md}from"@vkontakte/videoplayer-shared/evergreen";var $s=(n,e,t,{equal:i=(a,o)=>a===o,changed$:r,onError:s}={})=>{let a=n.getState(),o=e(),u=hd(r),l=new md;return r&&l.add(r.subscribe(p=>{let c=n.getState();i(p,c)&&n.setState(p)},s)),i(o,a)||(t(a),u&&n.setState(a)),l.add(n.stateChangeStarted$.subscribe(p=>{t(p.to),u&&n.setState(p.to)},s)),l},dt=(n,e,t)=>$s(e,()=>n.loop,i=>{cn(i)&&(n.loop=i)},{onError:t}),_e=(n,e,t,i)=>$s(e,()=>({muted:n.muted,volume:n.volume}),r=>{cn(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),et=(n,e,t,i)=>$s(e,()=>n.playbackRate,r=>{cn(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Ni=$s;var vd=n=>["__",n.language,n.label].join("|"),yd=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},dn=class n{constructor(e){this.available$=new su;this.current$=new gd(void 0);this.error$=new su;this.subscription=new bd;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Sd.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ni(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{pt(s)&&this.setInternal(s)},{equal:(s,a)=>pt(s)&&pt(a)&&s.length===a.length&&s.every(({id:o},u)=>o===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Ni(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{pt(s)&&this.setExternal(s)},{equal:(s,a)=>pt(s)&&pt(a)&&s.length===a.length&&s.every(({id:o},u)=>o===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Ni(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Ni(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ui(this.video);let{textTracks:e}=this.video;this.subscription.add(hi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(tu(hi(e,"addtrack"),hi(e,"removetrack"),iu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ru((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(tu(hi(e,"change"),iu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Hi(i=>i&&this.htmlTextTrackToITextTrack(i).id),ru()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(hi(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(hi(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;pt(t.align)&&(r.align=t.align),pt(t.position)&&(r.position=t.position),pt(t.size)&&(r.size=t.size),pt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ui(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:vd(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ui(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(fd(e)||!yd(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){Ui(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){Ui(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},tt=dn;var Zt=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 au=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pn=n=>{let e=au(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},nu=n=>{let e=au(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as $e,map as ht,merge as _s,filterChanged as hu,isNonNullable as mu,Subject as Md,filter as mn,mapTo as fn,combine as Ld,once as Bd,throttle as $d,ErrorCategory as Rd,ValueSubject as fu,Subscription as Dd}from"@vkontakte/videoplayer-shared/evergreen";var Td=3,ou=(n,e,t=Td)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),o=n.end(s);if(a<=e&&e<=o){if(i=a,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=s+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var Rs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var ji=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ds=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ji()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Vs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,mi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),uu=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Cs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Id=document.createElement("video"),xd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ed='video/mp4; codecs="hev1.1.6.L93.B0"',lu='video/webm; codecs="vp09.00.10.08"',cu='video/webm; codecs="av01.0.00M.08"',kd='audio/mp4; codecs="mp4a.40.2"',wd='audio/webm; codecs="opus"',du,Ad=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:cu}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:lu}})]);du={DASH_WEBM_AV1:e,DASH_WEBM:t}};Ad().catch(n=>{console.log(Id),console.error(n)});var Os=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return du}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:mi(),mse:uu(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Je()?.isTypeSupported?.(xd),t=!!Je()?.isTypeSupported?.(Ed),i=!!Je()?.isTypeSupported?.(kd);this._codecs={h264:e,h265:t,vp9:!!Je()?.isTypeSupported?.(lu),av1:!!Je()?.isTypeSupported?.(cu),aac:i,opus:!!Je()?.isTypeSupported?.(wd),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var pu="audio/mpeg",Fs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(pu)},this._codecs={mp3:!!Je()?.isTypeSupported?.(pu)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as Pd}from"@vkontakte/videoplayer-shared/evergreen";var hn=class{constructor(){this.isInited$=new Pd(!1);this._displayChecker=new Vs,this._deviceChecker=new Ds(this._displayChecker),this._browserChecker=new Rs,this._videoChecker=new Os(this._deviceChecker,this._browserChecker),this._audioChecker=new Fs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},O=new hn;var Ne=n=>{let e=g=>$e(n,g).pipe(fn(void 0)),t=new Dd,i=()=>t.unsubscribe(),r=_s($e(n,"progress"),$e(n,"timeupdate")).pipe(ht(()=>ou(n.buffered,n.currentTime))),s=O.browser.isSafari?Ld({play:e("play").pipe(Bd()),playing:e("playing")}).pipe(fn(void 0)):e("playing"),a=$e(n,"volumechange").pipe(ht(()=>({muted:n.muted,volume:n.volume}))),o=$e(n,"ratechange").pipe(ht(()=>n.playbackRate)),u=$e(n,"error").pipe(mn(()=>!!(n.error||n.played.length)),ht(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:Rd.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=$e(n,"timeupdate").pipe(ht(()=>n.currentTime)),p=["waiting","seeking","seeked","timeupdate"],c=new Md,d=.3,h;t.add(_s(...p.map(g=>$e(n,g))).subscribe(g=>{let R=n.currentTime;n.loop&&mu(h)&&mu(R)&&h>=n.duration-d&&R<=d&&c.next(h),h=R}));let m=e("pause").pipe(mn(()=>!n.error&&h!==n.duration)),f=$e(n,"enterpictureinpicture"),b=$e(n,"leavepictureinpicture"),S=new fu(nu(n));t.add(f.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let x=new fu(pn(n)),v=$e(n,"fullscreenchange");t.add(v.pipe(ht(()=>pn(n))).subscribe(x));let I=.1,E=1e3,L=$e(n,"timeupdate").pipe(ht(g=>n.duration-n.currentTime<I),hu()),V=_s(L.pipe(mn(g=>!n.loop&&g)),$e(n,"ended")).pipe($d(E),fn(void 0)),w=_s(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>$e(n,g)),L.pipe(ht(g=>({type:g?"ended":"unknown"})))).pipe(ht(g=>O.browser.isFirefox&&g.type==="ended"?n.readyState<2:n.readyState<3),hu());return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:V,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(n,"durationchange").pipe(ht(()=>n.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:a,playbackRateState$:o,inPiP$:S,inFullscreen$:x,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/evergreen";var Ft=n=>{switch(n){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};import{isNonNullable as K,isNullable as zs,now as ku,isHigher as Qs,isHigherOrEqual as bi,isInvariantQuality as Ws,isLowerOrEqual as gi,videoSizeToQuality as wu,assertNotEmptyArray as qs,assertNonNullable as Au}from"@vkontakte/videoplayer-shared/evergreen";var bn=!1,wt={},bu=n=>{bn=n},gu=()=>{wt={}},Su=n=>{n(wt)},zi=(n,e)=>{bn&&(wt.meta=wt.meta??{},wt.meta[n]=e)},Re=class{constructor(e){this.name=e}next(e){if(!bn)return;wt.series=wt.series??{};let t=wt.series[this.name]??[];t.push([Date.now(),e]),wt.series[this.name]=t}};import{isHigher as Vd,isHigherOrEqual as jg,isLower as vu,isLowerOrEqual as zg,isNonNullable as Ns,isNullable as Cd,videoHeightToQuality as Us}from"@vkontakte/videoplayer-shared/evergreen";function gn(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function Hs(n,e,t){return!!n&&gn(n,e,t)==="high_quality"}function fi(n,e,t){return Cd(n)||Ns(n.min)&&Ns(n.max)&&vu(n.max,n.min)||Ns(n.min)&&e&&Vd(n.min,e)||Ns(n.max)&&t&&vu(n.max,t)}function yu({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return fi({max:n?.max?Us(n.max):void 0,min:n?.min?Us(n.min):void 0},e?Us(e):void 0,t?Us(t):void 0)}var Pu=new Re("best_bitrate"),Gs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Si=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),_t=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ku()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ys='Assertion "ABR Tracks is empty array" failed',js=new WeakMap,Tu=new WeakMap,Iu=new WeakMap,Qi=(n,e,t,i)=>{let r=[...e].sort(Si(1)),s=[...t].sort(Si(1)),a=s.filter(u=>K(u.bitrate)&&K(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return o&&a.includes(o)?o:a.length?a.at(-1):s.at(0)},Wi=(n,e,t,i)=>{let r=js.get(e);r||(r=[...e].sort(Si(1)),js.set(e,r));let s=js.get(t);s||(s=[...t].sort(Si(1)),js.set(t,s));let a=Iu.get(n);a||(a=s.filter(u=>K(u.bitrate)&&K(n.bitrate)?n.bitrate/u.bitrate>i:!0),Iu.set(n,a));let o=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return o&&a.includes(o)?o:a.length?a.at(-1):s.at(0)},xu=n=>"quality"in n,Ks=(n,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&ku()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let o=xu(a)?"video":"audio",u=xu(a)?a.quality:a.bitrate;return e({message:`
7
- [last ${o} selected] ${u}
8
- `}),a}return i?.recordSwitch(t),t},Od=(n,e)=>Math.log(e)/Math.log(n),Mu=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&O.display.pixelRatio){let s=O.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(s-1)+1;else{let a=n.pixelRatioLogBase,[o=0,u=0,l=0]=n.pixelRatioLogCoefficients,p=Od(a,o*s+u)+l;Number.isFinite(p)&&(r*=p)}}return Hs(t,n.highQualityLimit,n.trafficSavingLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Eu=new WeakMap,mt=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{qs(n,Ys);let{containerSizeFactor:b,containerSizeLimit:S}=Mu({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&K(o)?o:1,v=Eu.get(n);v||(v=n.filter(T=>!Ws(T.quality)).sort((T,A)=>Qs(T.quality,A.quality)?-1:1),Eu.set(n,v));let I=v.at(-1)?.quality,E=v.at(0)?.quality,L=fi(r,E,I),V=x*Gs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},w=null;for(let T of v){let A=!0;if(S)if(T.size)A=T.size.width<=S.width&&T.size.height<=S.height;else{let M=S&&wu(S);A=M?gi(T.quality,M):!0}if(!A){k[T.quality]="FitsContainer";continue}let ee=h||t,$=K(ee)&&isFinite(ee)&&K(T.bitrate)?ee-s>=T.bitrate*V:!0,N=Hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===T.quality;if(!$&&!N){k[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Qs(T.quality,u.quality)){k[T.quality]="Buffer";continue}if(!!c&&bi(T.quality,c)&&!N){k[T.quality]="DroppedFramesLimit";continue}if(!!d&&bi(T.quality,d)&&!N){k[T.quality]="StallsLimit";continue}let se=L||(zs(r?.max)||gi(T.quality,r.max))&&(zs(r?.min)||bi(T.quality,r.min)),X=K(p)&&!p?gi(T.quality,i.backgroundVideoQualityLimit):!0;if(!se||!X){k[T.quality]="FitsQualityLimits";continue}w||(w=T)}w&&w.bitrate&&Pu.next(w.bitrate);let g=w??v.at(-1)??n[0],R=l?.last,y=Ks(i,m,g,l);return K(l)&&y.quality!==R?.quality&&m({message:`
6
+ var Yn="2.0.136-beta.0";var Se=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Se||{}),et=(v=>(v.MPEG="MPEG",v.DASH="DASH",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_STREAMS="DASH_STREAMS",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))(et||{});var Wr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Wr||{}),va=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(va||{});var ya=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(ya||{}),qr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(qr||{});import{assertNever as to,assertNonNullable as tc,isNonNullable as Gr,ValueSubject as Ta,Subject as ic,Subscription as rc,merge as sc,observableFrom as ac,fromEvent as Xn,map as Jn,tap as Zn,filterChanged as nc,isNullable as Ia,ErrorCategory as eo}from"@vkontakte/videoplayer-shared/evergreen";var Kn=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Yr=class{constructor(e){this.connection$=new Ta(void 0);this.castState$=new Ta("NOT_AVAILABLE");this.errorEvent$=new ic;this.realCastState$=new Ta("NOT_AVAILABLE");this.subscription=new rc;this.isDestroyed=!1;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 i=Gr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Kn("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:eo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Gr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ia(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ia(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Xn(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return to(r.sessionState)}})).add(sc(Xn(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Zn(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Jn(r=>r.castState)),ac([i.getCastState()])).pipe(nc(),Jn(oc),Zn(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Gr(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();tc(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Ia(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Gr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:eo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},oc=n=>{switch(n){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 to(n)}};import{assertNever as io}from"@vkontakte/videoplayer-shared/evergreen";var ee=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:io(t)}return n},pt=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:io(e)}};var w=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as uc,Subject as Kr,merge as ro}from"@vkontakte/videoplayer-shared/evergreen";var C=class{constructor(e){this.transitionStarted$=new Kr;this.transitionEnded$=new Kr;this.transitionUpdated$=new Kr;this.forceChanged$=new Kr;this.stateChangeStarted$=ro(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ro(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||uc(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as lc}from"@vkontakte/videoplayer-shared/evergreen";var so=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":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 lc(n)}};import{assertNever as qt,assertNonNullable as Lt,debounce as ao,ErrorCategory as no,fromEvent as $t,isNonNullable as oo,map as uo,merge as lo,observableFrom as cc,Subject as dc,Subscription as Ea,timeout as hc,getHighestQuality as pc}from"@vkontakte/videoplayer-shared/evergreen";var mc=5,fc=5,bc=500,co=7e3,Ei=class{constructor(e){this.subscription=new Ea;this.loadMediaTimeoutSubscription=new Ea;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:qt(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:qt(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:qt(e)}break}default:qt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(so(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 Ea;this.subscription.add(e),this.subscription.add(lo(this.videoState.stateChangeStarted$.pipe(uo(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(uo(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new dc;e.add(r.pipe(ao(bc)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let u=a.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>mc)&&r.next(u),s=u})),e.add($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,u=this.params.output.isBuffering$.getValue(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<fc&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:qt(a)}}),t($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t($t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=lo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cc(["init"])).pipe(ao(0));t(i,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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];Lt(l);let c=pc(Object.keys(l));Lt(c);let h=l[c];Lt(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Lt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Lt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Lt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Lt(l),i=ee(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:no.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return qt(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return oo(u)&&(a.metadata.title=u),oo(o)&&(a.metadata.subtitle=o),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(hc(co).subscribe(()=>s(`timeout(${co})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:no.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as po}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as gc}from"@vkontakte/videoplayer-shared/evergreen";var ho=n=>{try{n.pause(),n.playbackRate=0,gc(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Sc,Subscription as vc}from"@vkontakte/videoplayer-shared/evergreen";var xa=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)}},ka=window.WeakMap?new WeakMap:new xa,wa=window.WeakMap?new WeakMap:new Map,yc=(n,e=20)=>{let t=0;return Sc(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ve=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?po(i):(i=document.createElement("video"),n.appendChild(i)),ka.set(i,r);let s=new vc;return s.add(yc(i,e)),wa.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ye=n=>{wa.get(n)?.unsubscribe(),wa.delete(n);let t=ka.get(n);ka.delete(n),t?po(n):ho(n)};import{assertNonNullable as ki,isNonNullable as qe,isNullable as Ec,fromEvent as Gt,merge as mo,observableFrom as fo,filterChanged as bo,map as wi,Subject as go,Subscription as xc,ValueSubject as kc,ErrorCategory as wc}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Aa,isNullable as Tc,Subscription as Ic}from"@vkontakte/videoplayer-shared/evergreen";var Xr=(n,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=n.getState(),u=e(),o=Tc(r),l=new Ic;return r&&l.add(r.subscribe(c=>{let h=n.getState();i(c,h)&&n.setState(c)},s)),i(u,a)||(t(a),o&&n.setState(a)),l.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),o&&n.setState(c.to)},s)),l},We=(n,e,t)=>Xr(e,()=>n.loop,i=>{Aa(i)&&(n.loop=i)},{onError:t}),Te=(n,e,t,i)=>Xr(e,()=>({muted:n.muted,volume:n.volume}),r=>{Aa(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(n,e,t,i)=>Xr(e,()=>n.playbackRate,r=>{Aa(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),xi=Xr;var Ac=n=>["__",n.language,n.label].join("|"),Lc=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},La=class n{constructor(e){this.available$=new go;this.current$=new kc(void 0);this.error$=new go;this.subscription=new xc;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:wc.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(xi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{qe(s)&&this.setInternal(s)},{equal:(s,a)=>qe(s)&&qe(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(wi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(xi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{qe(s)&&this.setExternal(s)},{equal:(s,a)=>qe(s)&&qe(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(wi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(xi(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(xi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ki(this.video);let{textTracks:e}=this.video;this.subscription.add(Gt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(mo(Gt(e,"addtrack"),Gt(e,"removetrack"),fo(["init"])).pipe(wi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),bo((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(mo(Gt(e,"change"),fo(["init"])).pipe(wi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),wi(i=>i&&this.htmlTextTrackToITextTrack(i).id),bo()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Gt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Gt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;qe(t.align)&&(r.align=t.align),qe(t.position)&&(r.position=t.position),qe(t.size)&&(r.size=t.size),qe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ki(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Ac(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ki(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Ec(e)||!Lc(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){ki(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){ki(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Be=La;var Pt=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 So=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},$a=n=>{let e=So(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},vo=n=>{let e=So(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as me,map as Ge,merge as ss,filterChanged as wo,isNonNullable as Ao,Subject as Oc,filter as Ma,mapTo as Ra,combine as Fc,once as _c,shareReplay as fe,throttle as Nc,ErrorCategory as Uc,ValueSubject as Lo,Subscription as Hc}from"@vkontakte/videoplayer-shared/evergreen";var $c=3,yo=(n,e,t=$c)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),u=n.end(s);if(a<=e&&e<=u){if(i=a,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)n.end(o)+t>=i&&(i=n.start(o));for(let o=s+1;o<n.length;o++)n.start(o)-t<=r&&(r=n.end(o))}}return{from:i,to:r}};var Jr=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Ai=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Zr=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Ai()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var es=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ae=()=>window.ManagedMediaSource||window.MediaSource,Yt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),To=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ts=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Pc=document.createElement("video"),Mc='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Rc='video/mp4; codecs="hev1.1.6.L93.B0"',Io='video/webm; codecs="vp09.00.10.08"',Eo='video/webm; codecs="av01.0.00M.08"',Dc='audio/mp4; codecs="mp4a.40.2"',Bc='audio/webm; codecs="opus"',xo,Vc=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Eo}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Io}})]);xo={DASH_WEBM_AV1:e,DASH_WEBM:t}};Vc().catch(n=>{console.log(Pc),console.error(n)});var is=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return xo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Yt(),mse:To(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ae()?.isTypeSupported?.(Mc),t=!!Ae()?.isTypeSupported?.(Rc),i=!!Ae()?.isTypeSupported?.(Dc);this._codecs={h264:e,h265:t,vp9:!!Ae()?.isTypeSupported?.(Io),av1:!!Ae()?.isTypeSupported?.(Eo),aac:i,opus:!!Ae()?.isTypeSupported?.(Bc),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var ko="audio/mpeg",rs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(ko)},this._codecs={mp3:!!Ae()?.isTypeSupported?.(ko)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as Cc}from"@vkontakte/videoplayer-shared/evergreen";var Pa=class{constructor(){this.isInited$=new Cc(!1);this._displayChecker=new es,this._deviceChecker=new Zr(this._displayChecker),this._browserChecker=new Jr,this._videoChecker=new is(this._deviceChecker,this._browserChecker),this._audioChecker=new rs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},B=new Pa;var Ie=n=>{let e=y=>me(n,y).pipe(Ra(void 0),fe(1)),t=new Hc,i=()=>t.unsubscribe(),r=ss(me(n,"progress"),me(n,"timeupdate")).pipe(Ge(()=>yo(n.buffered,n.currentTime)),fe(1)),s=B.browser.isSafari?Fc({play:e("play").pipe(_c()),playing:e("playing")}).pipe(Ra(void 0),fe(1)):e("playing"),a=me(n,"volumechange").pipe(Ge(()=>({muted:n.muted,volume:n.volume})),fe(1)),u=me(n,"ratechange").pipe(Ge(()=>n.playbackRate),fe(1)),o=me(n,"error").pipe(Ma(()=>!!(n.error||n.played.length)),Ge(()=>{let y=n.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:Uc.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:n.error??void 0}}),fe(1)),l=me(n,"timeupdate").pipe(Ge(()=>n.currentTime),fe(1)),c=["waiting","seeking","seeked","timeupdate"],h=new Oc,d=.3,p;t.add(ss(...c.map(y=>me(n,y))).subscribe(y=>{let O=n.currentTime;n.loop&&Ao(p)&&Ao(O)&&p>=n.duration-d&&O<=d&&h.next(p),p=O}));let m=e("pause").pipe(Ma(()=>!n.error&&p!==n.duration),fe(1)),f=me(n,"enterpictureinpicture").pipe(fe(1)),b=me(n,"leavepictureinpicture").pipe(fe(1)),g=new Lo(vo(n));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let x=new Lo($a(n)),v=me(n,"fullscreenchange").pipe(fe(1));t.add(v.pipe(Ge(()=>$a(n))).subscribe(x));let I=.1,k=1e3,L=me(n,"timeupdate").pipe(Ge(y=>n.duration-n.currentTime<I),wo(),fe(1)),P=ss(L.pipe(Ma(y=>!n.loop&&y)),me(n,"ended")).pipe(Nc(k),Ra(void 0),fe(1)),$=ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>me(n,y)),L.pipe(Ge(y=>({type:y?"ended":"unknown"})))).pipe(Ge(y=>B.browser.isFirefox&&y.type==="ended"?n.readyState<2:n.readyState<3),wo(),fe(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:P,looped$:h,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:me(n,"durationchange").pipe(Ge(()=>n.duration),fe(1)),isBuffering$:$,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:x,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=n=>{switch(n){case"mobile":return mt.Q_144P;case"lowest":return mt.Q_240P;case"low":return mt.Q_360P;case"sd":case"medium":return mt.Q_480P;case"hd":case"high":return mt.Q_720P;case"fullhd":case"full":return mt.Q_1080P;case"quadhd":case"quad":return mt.Q_1440P;case"ultrahd":case"ultra":return mt.Q_2160P}};import{isNonNullable as G,isNullable as ls,now as Fo,isHigher as cs,isHigherOrEqual as Xt,isInvariantQuality as ds,isLowerOrEqual as Jt,videoSizeToQuality as _o,assertNotEmptyArray as hs,assertNonNullable as No}from"@vkontakte/videoplayer-shared/evergreen";var Da=!1,it={},$o=n=>{Da=n},Po=()=>{it={}},Mo=n=>{n(it)},Li=(n,e)=>{Da&&(it.meta=it.meta??{},it.meta[n]=e)},be=class{constructor(e){this.name=e}next(e){if(!Da)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Qc,isHigherOrEqual as Pb,isLower as Ro,isLowerOrEqual as Mb,isNonNullable as as,isNullable as jc,videoHeightToQuality as ns}from"@vkontakte/videoplayer-shared/evergreen";function Ba(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function os(n,e,t){return!!n&&Ba(n,e,t)==="high_quality"}function Kt(n,e,t){return jc(n)||as(n.min)&&as(n.max)&&Ro(n.max,n.min)||as(n.min)&&e&&Qc(n.min,e)||as(n.max)&&t&&Ro(n.max,t)}function Do({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Kt({max:n?.max?ns(n.max):void 0,min:n?.min?ns(n.min):void 0},e?ns(e):void 0,t?ns(t):void 0)}var Uo=new be("best_bitrate"),ps=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Zt=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Fo()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ms='Assertion "ABR Tracks is empty array" failed',us=new WeakMap,Bo=new WeakMap,Vo=new WeakMap,$i=(n,e,t,i)=>{let r=[...e].sort(Zt(1)),s=[...t].sort(Zt(1)),a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Pi=(n,e,t,i)=>{let r=us.get(e);r||(r=[...e].sort(Zt(1)),us.set(e,r));let s=us.get(t);s||(s=[...t].sort(Zt(1)),us.set(t,s));let a=Vo.get(n);a||(a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),Vo.set(n,a));let u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Co=n=>"quality"in n,fs=(n,e,t,i)=>{let r=G(i?.last?.bitrate)&&G(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Fo()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let u=Co(a)?"video":"audio",o=Co(a)?a.quality:a.bitrate;return e({message:`
7
+ [last ${u} selected] ${o}
8
+ `}),a}return i?.recordSwitch(t),t},zc=(n,e)=>Math.log(e)/Math.log(n),Ho=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&B.display.pixelRatio){let s=B.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(s-1)+1;else{let a=n.pixelRatioLogBase,[u=0,o=0,l=0]=n.pixelRatioLogCoefficients,c=zc(a,u*s+o)+l;Number.isFinite(c)&&(r*=c)}}return os(t,n.highQualityLimit,n.trafficSavingLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Oo=new WeakMap,Ye=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:h,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{hs(n,ms);let{containerSizeFactor:b,containerSizeLimit:g}=Ho({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&G(u)?u:1,v=Oo.get(n);v||(v=n.filter(S=>!ds(S.quality)).sort((S,T)=>cs(S.quality,T.quality)?-1:1),Oo.set(n,v));let I=v.at(-1)?.quality,k=v.at(0)?.quality,L=Kt(r,k,I),P=x*ps(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},$=null;for(let S of v){let T=!0;if(g)if(S.size)T=S.size.width<=g.width&&S.size.height<=g.height;else{let H=g&&_o(g);T=H?Jt(S.quality,H):!0}if(!T){E[S.quality]="FitsContainer";continue}let z=p||t,R=G(z)&&isFinite(z)&&G(S.bitrate)?z-s>=S.bitrate*P:!0,N=os(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===S.quality;if(!R&&!N){E[S.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&o&&!ds(o.quality)&&(a??0)<i.minBufferToSwitchUp&&cs(S.quality,o.quality)){E[S.quality]="Buffer";continue}if(!!h&&Xt(S.quality,h)&&!N){E[S.quality]="DroppedFramesLimit";continue}if(!!d&&Xt(S.quality,d)&&!N){E[S.quality]="StallsLimit";continue}let ne=L||(ls(r?.max)||Jt(S.quality,r.max))&&(ls(r?.min)||Xt(S.quality,r.min)),oe=G(c)&&!c?Jt(S.quality,i.backgroundVideoQualityLimit):!0;if(!ne||!oe){E[S.quality]="FitsQualityLimits";continue}$||($=S)}$&&$.bitrate&&Uo.next($.bitrate);let y=$??v.at(-1)??n[0],O=l?.last,M=fs(i,m,y,l);return G(l)&&M.quality!==O?.quality&&m({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
- ${n.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
11
+ ${n.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate}, size: ${S.size?.width}:${S.size?.height} }`).join(`
12
12
  `)}
13
13
 
14
14
  [tuning]
15
- ${Object.entries(i??{}).map(([T,A])=>`${T}: ${A}`).join(`
15
+ ${Object.entries(i??{}).map(([S,T])=>`${S}: ${T}`).join(`
16
16
  `)}
17
17
 
18
18
  [limit params]
19
19
  containerSizeFactor: ${b},
20
- containerSizeLimit: ${S?.width??0} x ${S?.height??0},
20
+ containerSizeLimit: ${g?.width??0} x ${g?.height??0},
21
21
  estimatedThroughput: ${t},
22
- stallsPredictedThroughput: ${h},
22
+ stallsPredictedThroughput: ${p},
23
23
  reserve: ${s},
24
- playbackRate: ${o},
24
+ playbackRate: ${u},
25
25
  playbackRateFactor: ${x},
26
26
  forwardBufferHealth: ${a},
27
- bitrateFactor: ${V},
27
+ bitrateFactor: ${P},
28
28
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
29
- droppedVideoMaxQualityLimit: ${c},
29
+ droppedVideoMaxQualityLimit: ${h},
30
30
  stallsVideoMaxQualityLimit: ${d},
31
31
  limitsAreInvalid: ${L},
32
32
  maxQualityLimit: ${r?.max},
33
33
  minQualityLimit: ${r?.min},
34
34
 
35
35
  [limited video tracks]
36
- ${Object.entries(k).map(([T,A])=>`${T}: ${A}`).join(`
36
+ ${Object.entries(E).map(([S,T])=>`${S}: ${T}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${w?.quality}
40
- [selected video track] ${y?.quality}
41
- `}),y},Xs=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{qs(n,Ys);let{containerSizeFactor:b,containerSizeLimit:S}=Mu({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&K(o)?o:1,v=n.filter(A=>!Ws(A.quality)).sort((A,ee)=>Qs(A.quality,ee.quality)?-1:1),I=v.at(-1)?.quality,E=v.at(0)?.quality,L=fi(r,E,I),V=x*Gs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},g=v.filter(A=>{let ee=!0;if(S)if(A.size)ee=A.size.width<=S.width&&A.size.height<=S.height;else{let D=S&&wu(S);ee=D?gi(A.quality,D):!0}if(!ee)return k[A.quality]="FitsContainer",!1;let $=h||t,N=K($)&&isFinite($)&&K(A.bitrate)?$-s>=A.bitrate*V:!0,Y=Hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===A.quality;if(!N&&!Y)return k[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Qs(A.quality,u.quality))return k[A.quality]="Buffer",!1;if(!!c&&bi(A.quality,c)&&!Y)return k[A.quality]="DroppedFramesLimit",!1;if(!!d&&bi(A.quality,d)&&!Y)return k[A.quality]="StallsLimit",!1;let X=L||(zs(r?.max)||gi(A.quality,r.max))&&(zs(r?.min)||bi(A.quality,r.min)),M=K(p)&&!p?gi(A.quality,i.backgroundVideoQualityLimit):!0;return!X||!M?(k[A.quality]="FitsQualityLimits",!1):!0})[0];g&&g.bitrate&&Pu.next(g.bitrate);let R=g??v.at(-1)??n[0],y=l?.last,T=Ks(i,m,R,l);return K(l)&&T.quality!==y?.quality&&m({message:`
39
+ [best video track] ${$?.quality}
40
+ [selected video track] ${M?.quality}
41
+ `}),M},bs=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:h,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{hs(n,ms);let{containerSizeFactor:b,containerSizeLimit:g}=Ho({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&G(u)?u:1,v=n.filter(T=>!ds(T.quality)).sort((T,z)=>cs(T.quality,z.quality)?-1:1),I=v.at(-1)?.quality,k=v.at(0)?.quality,L=Kt(r,k,I),P=x*ps(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},y=v.filter(T=>{let z=!0;if(g)if(T.size)z=T.size.width<=g.width&&T.size.height<=g.height;else{let F=g&&_o(g);z=F?Jt(T.quality,F):!0}if(!z)return E[T.quality]="FitsContainer",!1;let R=p||t,N=G(R)&&isFinite(R)&&G(T.bitrate)?R-s>=T.bitrate*P:!0,Y=os(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===T.quality;if(!N&&!Y)return E[T.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&o&&!ds(o.quality)&&(a??0)<i.minBufferToSwitchUp&&cs(T.quality,o.quality))return E[T.quality]="Buffer",!1;if(!!h&&Xt(T.quality,h)&&!Y)return E[T.quality]="DroppedFramesLimit",!1;if(!!d&&Xt(T.quality,d)&&!Y)return E[T.quality]="StallsLimit",!1;let oe=L||(ls(r?.max)||Jt(T.quality,r.max))&&(ls(r?.min)||Xt(T.quality,r.min)),H=G(c)&&!c?Jt(T.quality,i.backgroundVideoQualityLimit):!0;return!oe||!H?(E[T.quality]="FitsQualityLimits",!1):!0})[0];y&&y.bitrate&&Uo.next(y.bitrate);let O=y??v.at(-1)??n[0],M=l?.last,S=fs(i,m,O,l);return G(l)&&S.quality!==M?.quality&&m({message:`
42
42
  [VIDEO TRACKS ABR]
43
43
  [available video tracks]
44
- ${n.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${A.size?.width}:${A.size?.height} }`).join(`
44
+ ${n.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${Object.entries(i??{}).map(([A,ee])=>`${A}: ${ee}`).join(`
48
+ ${Object.entries(i??{}).map(([T,z])=>`${T}: ${z}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
52
52
  containerSizeFactor: ${b},
53
- containerSizeLimit: ${S?.width??0} x ${S?.height??0},
53
+ containerSizeLimit: ${g?.width??0} x ${g?.height??0},
54
54
  estimatedThroughput: ${t},
55
- stallsPredictedThroughput: ${h},
55
+ stallsPredictedThroughput: ${p},
56
56
  reserve: ${s},
57
- playbackRate: ${o},
57
+ playbackRate: ${u},
58
58
  playbackRateFactor: ${x},
59
59
  forwardBufferHealth: ${a},
60
- bitrateFactor: ${V},
60
+ bitrateFactor: ${P},
61
61
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
62
- droppedVideoMaxQualityLimit: ${c},
62
+ droppedVideoMaxQualityLimit: ${h},
63
63
  stallsVideoMaxQualityLimit: ${d},
64
64
  limitsAreInvalid: ${L},
65
65
  maxQualityLimit: ${r?.max},
66
66
  minQualityLimit: ${r?.min},
67
67
 
68
68
  [limited video tracks]
69
- ${Object.entries(k).map(([A,ee])=>`${A}: ${ee}`).join(`
69
+ ${Object.entries(E).map(([T,z])=>`${T}: ${z}`).join(`
70
70
  `)||"All tracks are available"}
71
71
 
72
- [best video track] ${g?.quality}
73
- [selected video track] ${T?.quality}
74
- `}),T},Js=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{qs(t,Ys);let p=r.considerPlaybackRate&&K(s)?s:1,c=[...t].sort(Si(-1)),d=n.bitrate;Au(d);let h=p*Gs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Qi(n,e,t,r.minVideoAudioRatio),b=l||i;K(b)&&isFinite(b)&&(m=c.find(v=>K(v.bitrate)&&K(f?.bitrate)?b-d>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f);let S=o?.last,x=m&&Ks(r,u,m,o);return K(o)&&x?.bitrate!==S?.bitrate&&u({message:`
72
+ [best video track] ${y?.quality}
73
+ [selected video track] ${S?.quality}
74
+ `}),S},gs=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{hs(t,ms);let c=r.considerPlaybackRate&&G(s)?s:1,h=[...t].sort(Zt(-1)),d=n.bitrate;No(d);let p=c*ps(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=$i(n,e,t,r.minVideoAudioRatio),b=l||i;G(b)&&isFinite(b)&&(m=h.find(v=>G(v.bitrate)&&G(f?.bitrate)?b-d>=v.bitrate*p&&v.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,x=m&&fs(r,o,m,u);return G(u)&&x?.bitrate!==g?.bitrate&&o({message:`
75
75
  [AUDIO TRACKS ABR]
76
76
  [available audio tracks]
77
77
  ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
@@ -86,13 +86,13 @@ var Oo="2.0.135-dev.f94adb28.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",
86
86
  stallsPredictedThroughput: ${l},
87
87
  reserve: ${d},
88
88
  playbackRate: ${s},
89
- playbackRateFactor: ${p},
89
+ playbackRateFactor: ${c},
90
90
  forwardBufferHealth: ${a},
91
- bitrateFactor: ${h},
91
+ bitrateFactor: ${p},
92
92
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
93
93
 
94
94
  [selected audio track] ${x?.id}
95
- `}),x},Zs=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{qs(t,Ys);let p=r.considerPlaybackRate&&K(s)?s:1,c=Tu.get(t);c||(c=[...t].sort(Si(-1)),Tu.set(t,c));let d=n.bitrate;Au(d);let h=p*Gs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Wi(n,e,t,r.minVideoAudioRatio),b=l||i;K(b)&&isFinite(b)&&(m=c.find(v=>K(v.bitrate)&&K(f?.bitrate)?b-d>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f);let S=o?.last,x=m&&Ks(r,u,m,o);return K(o)&&x?.bitrate!==S?.bitrate&&u({message:`
95
+ `}),x},Ss=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{hs(t,ms);let c=r.considerPlaybackRate&&G(s)?s:1,h=Bo.get(t);h||(h=[...t].sort(Zt(-1)),Bo.set(t,h));let d=n.bitrate;No(d);let p=c*ps(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Pi(n,e,t,r.minVideoAudioRatio),b=l||i;G(b)&&isFinite(b)&&(m=h.find(v=>G(v.bitrate)&&G(f?.bitrate)?b-d>=v.bitrate*p&&v.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,x=m&&fs(r,o,m,u);return G(u)&&x?.bitrate!==g?.bitrate&&o({message:`
96
96
  [AUDIO TRACKS ABR]
97
97
  [available audio tracks]
98
98
  ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
@@ -107,20 +107,20 @@ var Oo="2.0.135-dev.f94adb28.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",
107
107
  stallsPredictedThroughput: ${l},
108
108
  reserve: ${d},
109
109
  playbackRate: ${s},
110
- playbackRateFactor: ${p},
110
+ playbackRateFactor: ${c},
111
111
  forwardBufferHealth: ${a},
112
- bitrateFactor: ${h},
112
+ bitrateFactor: ${p},
113
113
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
114
114
 
115
115
  [selected audio track] ${x?.id}
116
- `}),x};var Ee=n=>new URL(n).hostname;import{assertNever as Vu,assertNonNullable as Cu,combine as sp,debounce as ap,ErrorCategory as Ou,filter as Fu,filterChanged as np,isNonNullable as In,map as ra,merge as _u,observableFrom as op,once as up,Subscription as lp,ValueSubject as xn,videoQualityToHeight as Nu,videoSizeToQuality as cp}from"@vkontakte/videoplayer-shared/evergreen";var Lu=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},Ue=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!Lu(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return Lu(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ta,isNullable as Nd,assertNonNullable as Yi}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Bu,assertNonNullable as ea,now as Fd}from"@vkontakte/videoplayer-shared/evergreen";function Te(){return Fd()}function Sn(n){return Te()-n}function vn(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,o,u=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let l=a.indexOf("?")>-1?"&":"?";return u&&(a+=l+"lowLat=1",l="&"),o&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function $u(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function vi(n,e,t,i){let r=window.XMLHttpRequest,s,a,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;ea(p);let y=Sn(p),T;if(y<f){T=f-y,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,L()},S=y=>(s=y,R),x=y=>(c=y,R),v=()=>(h="json",R),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},E=y=>(d=y,R),L=()=>{p=Te(),a=new r,a.open("get",n);let y=0,T,A=0,ee=()=>(ea(p),Math.max(p,Math.max(T||0,A||0)));if(s&&a.addEventListener("progress",$=>{let N=Te();s.updateChunk&&$.loaded>y&&(s.updateChunk(ee(),$.loaded-y),y=$.loaded,T=N)}),o&&(a.timeout=o,a.addEventListener("timeout",()=>I())),a.addEventListener("load",()=>{if(u)return;ea(a);let $=a.status;if($>=200&&$<300){let{response:N,responseType:Y}=a,re=N?.byteLength;if(typeof re=="number"&&s){let he=re-y;he&&s.updateChunk&&s.updateChunk(ee(),he)}Y==="json"&&(!N||!Object.values(N).length)?I():(c&&c(),e(N))}else I()}),a.addEventListener("error",()=>{I()}),d){let $=()=>{ea(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(A=Te(),a.removeEventListener("readystatechange",$))};a.addEventListener("readystatechange",$)}return a.responseType=h,a.send(),R},R={withBitrateReporting:S,withParallel:E,withJSONResponse:v,withRetryCount:y=>(l=y,R),withRetryInterval:(y,T)=>(Bu(y)&&(f=y),Bu(T)&&(m=T),R),withTimeout:y=>(o=y,R),withFinally:x,send:L,abort:()=>{a&&(a.abort(),a=void 0),u=!0,c&&c()}};return R}var qi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,o=s.end-s.start;i+=a;let u=s.bytes*a/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>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 Gi=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){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,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._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=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,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}};import{Subject as Ud}from"@vkontakte/videoplayer-shared/evergreen";var ia=1e4,yn=3;var Hd=6e4,jd=10,zd=1,Qd=500,Ki=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Ud,this.chunkRateEstimator=new qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=vn(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(O.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!yu({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ta(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{$u(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gi(yn,ia,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,o=null,u=null,l=null,p=!1,c=()=>{let I=s&&(!p||p===this.rep);return I||t("Not running!"),I},d=(I,E,L)=>{u&&u.abort(),u=vi(this.urlResolver.resolve(I,!1),E,L,()=>this._retryCallback()).withTimeout(ia).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yn).withFinally(()=>{u=null}).send()},h=(I,E,L)=>{Yi(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},f=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=Te()-1e4,V=0;for(let w=0;w<this.bufferStates.length;w++){let g=this.bufferStates[w];I=Math.min(I,g.buf),g.ts<L&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let k=I-zd;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},S=I=>{let E,L=()=>E&&E.start?E.start.length:0,V=$=>E.start[$]/1e3,k=$=>E.dur[$]/1e3,w=$=>E.fragIndex+$,g=($,N)=>({chunkIdx:w($),startTS:V($),dur:k($),discontinuity:N}),R=()=>{let $=0;if(E&&E.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,re=N;this.sourceJitter>1&&(re+=this.sourceJitter-1);let he=E.dur.length-1;for(;he>=0&&(re-=E.dur[he],!(re<=0));--he);$=Math.min(he,E.dur.length-1-Y),$=Math.max($,0)}return g($,!0)},y=$=>{let N=L();if(!(N<=0)){if(ta($)){for(let Y=0;Y<N;Y++)if(V(Y)>$)return g(Y)}return R()}},T=$=>{let N=L(),Y=$?$.chunkIdx+1:0,re=Y-E.fragIndex;if(!(N<=0)){if(!$||re<0||re-N>jd)return t(`Resync: offset=${re} bChunks=${N} chunk=`+JSON.stringify($)),R();if(!(re>=N))return g(Y-E.fragIndex,!1)}},A=($,N,Y)=>{l&&l.abort(),l=vi(this.urlResolver.resolve($,!0,this.lowLatency),N,Y,()=>this._retryCallback()).withTimeout(ia).withRetryCount(yn).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,N)=>{A(I,Y=>{if(!c())return;E=Y;let re=!!E.lowLatency;re!==this.lowLatency&&f(re);let he=0;for(let se=0;se<E.dur.length;++se)he+=E.dur[se];he>0&&(Yi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(y(N))},()=>this._handleNetworkError())},nextChunk:T}},x=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Yi(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:I=>{let{videoElement:E,logger:L}=this.params,V=S(e.jidxUrl),k,w,g,R,y=0,T,A,ee,$=()=>{T&&(clearTimeout(T),T=void 0);let D=Math.max(Qd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=y+D,me=Te(),J=Math.min(1e4,Se-me);y=me;let fe=()=>{l||c()&&V.seek(()=>{c()&&(y=Te(),N(),$())})};J>0?T=window.setTimeout(()=>{this.paused?$():fe()},J):fe()},N=()=>{let D;for(;D=V.nextChunk(R);)R=D,X(D);let Se=V.nextChunk(g);if(Se){if(g&&Se.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?$():(x(),this._initPlayerWith(e));return}se(Se)}else $()},Y=(D,Se)=>{if(!c()||!this.sourceBuffer)return;let me,J,fe,ze=Pe=>{window.setTimeout(()=>{c()&&Y(D,Se)},Pe)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),ze(100);else{let Pe=Te(),oe=E.currentTime;!this.paused&&E.buffered.length>1&&A===oe&&Pe-ee>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),A!==oe&&(A=oe,ee=Pe);let Qe=this._getBufferSizeSec();if(Qe>30)L(`Buffered ${Qe} seconds; delaying appendBuffer`),ze(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Pe,buf:Qe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ge){if(ge.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),fe=this.sourceBuffer.buffered.length,fe!==0&&(me=this.sourceBuffer.buffered.start(0),J=oe,J-me>4&&this.sourceBuffer.remove(me,J-3)),ze(1e3);else throw ge}}},re=()=>{w&&k&&(L([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(g)]),Y(w,function(){w=null,N()}))},he=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),se=D=>{c()&&h(he(D),(Se,me)=>{if(c()){if(me/=1e3,w=Se,g=D,a=D.startTS,me){let J=Math.min(10,D.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*J:J}re()}},()=>this._handleNetworkError())},X=D=>{c()&&(Yi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(D),!1)))},M=D=>{c()&&(e.cachedHeader=D,Y(D,()=>{k=!0,re()}))};s=!0,V.seek(D=>{if(c()){if(y=Te(),!D){$();return}R=D,!Nd(I)||D.startTS>I?se(D):(g=D,N())}},I),e.cachedHeader?M(e.cachedHeader):d(e.headerUrl,M,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>a},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ta(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Yi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ta(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(d,h)=>{let m=Te();if(this.chunkRateEstimator.addInterval(d,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:b}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},a=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Sn(a)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=s.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=Te();c<o&&(a=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ia).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ue(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let o=[];return a?.length?(a.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Hd))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Wd,filter as Ru,fromEvent as qd,interval as Gd,isHigher as Yd,isInvariantQuality as Kd,isLower as Xd,merge as Jd,Subject as Du,Subscription as Zd}from"@vkontakte/videoplayer-shared/evergreen";var Tn=class{constructor(){this.onDroopedVideoFramesLimit$=new Du;this.subscription=new Zd;this.playing=!1;this.tracks=[];this.forceChecker$=new Du;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Kd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Yd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(qd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Gd(this.droppedFramesChecker.checkTime).pipe(Ru(()=>this.playing),Ru(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Wd(this.droppedFramesChecker.checkTime)),i=Jd(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Xd(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},yi=Tn;import{map as ep,Observable as tp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as ip}from"@vkontakte/videoplayer-shared/evergreen";var Xi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var rp=(n,e)=>new tp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,o)=>{a.forEach(u=>t.next(u.isIntersecting||Xi()))},{...i,...e});r.observe(n);let s=ip(document,"visibilitychange").pipe(ep(a=>!document.hidden||Xi())).subscribe(a=>t.next(a));return()=>{r.unobserve(n),s.unsubscribe()}}),it=rp;var dp=["paused","playing","ready"],pp=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new lp;this.videoState=new _("stopped");this.representations$=new xn([]);this.droppedFramesManager=new yi;this.maxSeekBackTime$=new xn(1/0);this.zeroTime$=new xn(void 0);this.liveOffset=new Zt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Ou.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=Ft(r.name)??cp(r.video),o=r.bitrate/1e3,u={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),In(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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 a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(pp.includes(e)&&(a||o)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&dp.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(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(pe(this.params.source.url,u))}return;default:return Vu(e)}};this.textTracksManager=new tt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ou.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(_u(this.videoState.stateChangeStarted$.pipe(ra(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ra(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(Ee(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ne(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ra(r=>r.map(({track:s})=>s)),Fu(r=>!!r.length),up()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(np(),ra(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(sp({zeroTime:this.zeroTime$.pipe(Fu(In)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(it(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Nu(r),min:s&&Nu(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Vu(r.to)}},t)).add(_u(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,op(["init"])).pipe(ap(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),Fe(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&In(t)?t:mt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput: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=r?.id,a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),a||u||s!==o){let l=e.find(({track:p})=>p.id===s)?.representation;Cu(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Cu(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(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(pe(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Uu=Ji;var Ie=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,s=n.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as hh,assertNonNullable as mh,debounce as fh,ErrorCategory as xl,filter as Wn,filterChanged as ka,fromEvent as bh,isNonNullable as El,isNullable as gh,map as qn,merge as wa,observableFrom as Gn,once as kl,Subscription as Sh}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Zi}from"@vkontakte/videoplayer-shared/evergreen";var sa=n=>{if(!n)return{id:"EmptyResponse",category:Zi.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Zi.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Zi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Zi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Zi.PARSER,message:"Response is valid XML, but parser failed"}};var ke=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as Fn,assertNonNullable as Ai,combine as Pi,ErrorCategory as ut,filter as ga,filterChanged as Br,flattenObject as $r,fromEvent as $t,getTraceSubscriptionMethod as Yp,interval as _n,isNonNullable as Rr,isNullable as gl,map as Mi,merge as ri,now as Nn,Subject as Sa,Subscription as Sl,tap as Kp,throttle as Xp,ValueSubject as ue}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as hp,ErrorCategory as Hu,Subject as ju}from"@vkontakte/videoplayer-shared/evergreen";var mp=18,zu=!1;try{zu=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=mp}catch(n){console.error(n)}var En=class{constructor(e){this.bufferFull$=new ju;this.error$=new ju;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Hu.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};zu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Hu.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:hp(t)}}},Qu=En;var Ti=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as Ut,assertNonNullable as He,ErrorCategory as Mt,fromEvent as $n,getExponentialDelay as Rn,isNonNullable as Ei,isNullable as we,now as na,once as Op,Subject as Fp,Subscription as _p,ValueSubject as ii}from"@vkontakte/videoplayer-shared/evergreen";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=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,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Ii=class extends j{};var er=class extends j{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,a=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(a);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var tr=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends j{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var rr=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ar=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var ei=class extends te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var nr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var or=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ur=class extends te{constructor(e,t){switch(super(e,t),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 lr=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var cr=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var dr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pr=class extends te{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()}};var hr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var br=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gr=class extends te{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())}};var Sr=class extends te{constructor(t,i){super(t,i);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 vr=class extends te{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var yr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Tr=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var bp={ftyp:tr,moov:ir,mvhd:rr,moof:sr,mdat:ar,sidx:ei,trak:nr,mdia:dr,mfhd:fr,tkhd:pr,traf:br,tfhd:gr,tfdt:Sr,trun:vr,minf:hr,sv3d:or,st3d:ur,prhd:lr,proj:mr,equi:cr,uuid:er,stbl:yr,stsd:Tr,avc1:Ir,unknown:Ii},At=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!a.size)break;t.push(a),i+=a.size}catch{break}return t}createBox(e,t){let i=bp[e];return i?new i(t,new n):new Ii(t,new n)}};var Nt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Sp=new TextDecoder("ascii"),vp=n=>Sp.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",yp=n=>{let e=new ei(n,new At),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,o})},Tp=(n,e)=>{let i=new At().parse(n),r=new Nt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let o=s[0],u=a[a.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Ip=n=>{let t=new At().parse(n),i=new Nt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},xp=n=>{let t=new At().parse(n);return new Nt(t).find("sidx")?.timescale},Ep=(n,e)=>{let i=new At().parse(n),s=new Nt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=a.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},kp=n=>{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}}},i=new At().parse(n),r=new Nt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Wu={validateData:vp,parseInit:kp,getIndexRange:()=>{},parseSegments:yp,parseFeedableSegmentChunk:Tp,getChunkEndTime:Ep,getServerLatencyTimestamps:Ip,getTimescaleFromIndex:xp};import{assertNonNullable as wn,isNonNullable as Ku,isNullable as Ap}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as wp}from"@vkontakte/videoplayer-shared/evergreen";var qu={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"}},Gu=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=xr(n,t),r=i in qu,s=r?qu[i].type:"binary",a=n.getUint8(t),o=0;a&128?o=1:a&64?o=2:a&32?o=3:a&16?o=4:a&8?o=5:a&4?o=6:a&2?o=7:a&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=a&255>>o,p=xr(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+d):h=new DataView(n.buffer,n.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},xr=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return xr(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:wp(e)}},ti=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Gu(i);if(!e(r))return;r.type==="master"&&ti(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Yu=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Gu(n);return ti(r.value,({tag:s,type:a,value:o})=>(s===17143?e=ot(o,a):s===17026?t=ot(o,a):s===17029&&(i=ot(o,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Xu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Pp=[231,22612,22743,167,171,163,160,175],Mp=n=>{let e,t,i,r,s=!1,a=!1,o=!1,u,l,p=!1,c=0;return ti(n,({tag:d,type:h,value:m,valueSize:f})=>{if(d===21419){let b=ot(m,h);l=xr(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=ot(m,h):d===17545?r=ot(m,h):d===21420&&l===475249515?u=ot(m,h):d===374648427?ti(m,({tag:b,type:S,value:x})=>b===30321?(p=ot(x,S)===1,!1):!0):s&&a&&Xu.includes(d)&&(o=!0),!o}),wn(e,"Failed to parse webm Segment start"),wn(t,"Failed to parse webm Segment end"),wn(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Lp=n=>{if(Ap(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Bp=(n,e)=>{let t=!1,i=!1,r=o=>Ku(o.time)&&Ku(o.position),s=[],a;return ti(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=ot(l,u));break;case 183:break;case 241:a&&(a.position=ot(l,u));break;default:t&&Xu.includes(o)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((o,u)=>{let{time:l,position:p}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},$p=n=>{let e=0,t=!1;try{ti(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Pp.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},Ju={validateData:Yu,parseInit:Mp,getIndexRange:Lp,parseSegments:Bp,parseFeedableSegmentChunk:$p};var Er=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ju;case"mp4":return Wu}}throw new ReferenceError(`Unsupported mime type ${n}`)};var xi=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),o=s+a;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Vp,isNullable as sl}from"@vkontakte/videoplayer-shared/evergreen";var aa=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Zu=n=>{try{let e=Rp(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(o=>{let u=a[o];(typeof u>"u"||u==="")&&delete a[o]}),a}return null}catch{return null}};function Rp(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
116
+ `}),x};var ue=n=>new URL(n).hostname;import{assertNever as Go,assertNonNullable as Yo,combine as hd,debounce as pd,ErrorCategory as Ko,filter as Xo,filterChanged as md,isNonNullable as _a,map as Is,merge as Jo,observableFrom as fd,once as bd,Subscription as gd,ValueSubject as Na,videoQualityToHeight as Zo,videoSizeToQuality as Sd}from"@vkontakte/videoplayer-shared/evergreen";var Qo=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},Ee=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!Qo(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return Qo(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ys,isNullable as Gc,assertNonNullable as Di}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as jo,assertNonNullable as vs,now as Wc}from"@vkontakte/videoplayer-shared/evergreen";function re(){return Wc()}function Va(n){return re()-n}function Ca(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,u,o=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let l=a.indexOf("?")>-1?"&":"?";return o&&(a+=l+"lowLat=1",l="&"),u&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function zo(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function ei(n,e,t,i){let r=window.XMLHttpRequest,s,a,u,o=!1,l=0,c,h,d=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;vs(c);let M=Va(c),S;if(M<f){S=f-M,setTimeout(b,S);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,L()},g=M=>(s=M,O),x=M=>(h=M,O),v=()=>(p="json",O),I=()=>{if(!o){if(--l>=0){b(),i&&i();return}o=!0,h&&h(),t&&t()}},k=M=>(d=M,O),L=()=>{c=re(),a=new r,a.open("get",n);let M=0,S,T=0,z=()=>(vs(c),Math.max(c,Math.max(S||0,T||0)));if(s&&a.addEventListener("progress",R=>{let N=re();s.updateChunk&&R.loaded>M&&(s.updateChunk(z(),R.loaded-M),M=R.loaded,S=N)}),u&&(a.timeout=u,a.addEventListener("timeout",()=>I())),a.addEventListener("load",()=>{if(o)return;vs(a);let R=a.status;if(R>=200&&R<300){let{response:N,responseType:Y}=a,Z=N?.byteLength;if(typeof Z=="number"&&s){let te=Z-M;te&&s.updateChunk&&s.updateChunk(z(),te)}Y==="json"&&(!N||!Object.values(N).length)?I():(h&&h(),e(N))}else I()}),a.addEventListener("error",()=>{I()}),d){let R=()=>{vs(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=re(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),O},O={withBitrateReporting:g,withParallel:k,withJSONResponse:v,withRetryCount:M=>(l=M,O),withRetryInterval:(M,S)=>(jo(M)&&(f=M),jo(S)&&(m=S),O),withTimeout:M=>(u=M,O),withFinally:x,send:L,abort:()=>{a&&(a.abort(),a=void 0),o=!0,h&&h()}};return O}var Mi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,u=s.end-s.start;i+=a;let o=s.bytes*a/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>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 Ri=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=re(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=re()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ei(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),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(){let e=this._getParallelRequestCount(),t=re();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){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,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,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}};import{Subject as Yc}from"@vkontakte/videoplayer-shared/evergreen";var Ts=1e4,Oa=3;var Kc=6e4,Xc=10,Jc=1,Zc=500,Bi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Yc,this.chunkRateEstimator=new Mi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ca(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=Ca(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!Do({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ys(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{zo(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ri(Oa,Ts,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,u=null,o=null,l=null,c=!1,h=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},d=(I,k,L)=>{o&&o.abort(),o=ei(this.urlResolver.resolve(I,!1),k,L,()=>this._retryCallback()).withTimeout(Ts).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Oa).withFinally(()=>{o=null}).send()},p=(I,k,L)=>{Di(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),k,L,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=I=>{let k=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${k}=>${I}`),i.playbackRate=I)},f=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=re()-1e4,P=0;for(let $=0;$<this.bufferStates.length;$++){let y=this.bufferStates[$];I=Math.min(I,y.buf),y.ts<L&&P++}this.bufferStates.splice(0,P),t(`update playback rate; minBuffer=${I} drop=${P} jitter=${this.sourceJitter}`);let E=I-Jc;this.sourceJitter>=0?E-=this.sourceJitter/2:this.sourceJitter-=1,E>3?m(1.15):E>1?m(1.1):E>.3?m(1.05):m(1)}},g=I=>{let k,L=()=>k&&k.start?k.start.length:0,P=R=>k.start[R]/1e3,E=R=>k.dur[R]/1e3,$=R=>k.fragIndex+R,y=(R,N)=>({chunkIdx:$(R),startTS:P(R),dur:E(R),discontinuity:N}),O=()=>{let R=0;if(k&&k.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=N;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let te=k.dur.length-1;for(;te>=0&&(Z-=k.dur[te],!(Z<=0));--te);R=Math.min(te,k.dur.length-1-Y),R=Math.max(R,0)}return y(R,!0)},M=R=>{let N=L();if(!(N<=0)){if(ys(R)){for(let Y=0;Y<N;Y++)if(P(Y)>R)return y(Y)}return O()}},S=R=>{let N=L(),Y=R?R.chunkIdx+1:0,Z=Y-k.fragIndex;if(!(N<=0)){if(!R||Z<0||Z-N>Xc)return t(`Resync: offset=${Z} bChunks=${N} chunk=`+JSON.stringify(R)),O();if(!(Z>=N))return y(Y-k.fragIndex,!1)}},T=(R,N,Y)=>{l&&l.abort(),l=ei(this.urlResolver.resolve(R,!0,this.lowLatency),N,Y,()=>this._retryCallback()).withTimeout(Ts).withRetryCount(Oa).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,N)=>{T(I,Y=>{if(!h())return;k=Y;let Z=!!k.lowLatency;Z!==this.lowLatency&&f(Z);let te=0;for(let ne=0;ne<k.dur.length;++ne)te+=k.dur[ne];te>0&&(Di(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,R(M(N))},()=>this._handleNetworkError())},nextChunk:S}},x=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),Di(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:k,logger:L}=this.params,P=g(e.jidxUrl),E,$,y,O,M=0,S,T,z,R=()=>{S&&(clearTimeout(S),S=void 0);let F=Math.max(Zc,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=M+F,he=re(),ie=Math.min(1e4,ge-he);M=he;let Me=()=>{l||h()&&P.seek(()=>{h()&&(M=re(),N(),R())})};ie>0?S=window.setTimeout(()=>{this.paused?R():Me()},ie):Me()},N=()=>{let F;for(;F=P.nextChunk(O);)O=F,oe(F);let ge=P.nextChunk(y);if(ge){if(y&&ge.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?R():(x(),this._initPlayerWith(e));return}ne(ge)}else R()},Y=(F,ge)=>{if(!h()||!this.sourceBuffer)return;let he,ie,Me,lt=He=>{window.setTimeout(()=>{h()&&Y(F,ge)},He)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),lt(100);else{let He=re(),we=k.currentTime;!this.paused&&k.buffered.length>1&&T===we&&He-z>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),T!==we&&(T=we,z=He);let ct=this._getBufferSizeSec();if(ct>30)L(`Buffered ${ct} seconds; delaying appendBuffer`),lt(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:ct}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Qe){if(Qe.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(he=this.sourceBuffer.buffered.start(0),ie=we,ie-he>4&&this.sourceBuffer.remove(he,ie-3)),lt(1e3);else throw Qe}}},Z=()=>{$&&E&&(L([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(y)]),Y($,function(){$=null,N()}))},te=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),ne=F=>{h()&&p(te(F),(ge,he)=>{if(h()){if(he/=1e3,$=ge,y=F,a=F.startTS,he){let ie=Math.min(10,F.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ie:ie}Z()}},()=>this._handleNetworkError())},oe=F=>{h()&&(Di(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(F),!1)))},H=F=>{h()&&(e.cachedHeader=F,Y(F,()=>{E=!0,Z()}))};s=!0,P.seek(F=>{if(h()){if(M=re(),!F){R();return}O=F,!Gc(I)||F.startTS>I?ne(F):(y=F,N())}},I),e.cachedHeader?H(e.cachedHeader):d(e.headerUrl,H,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>a},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ys(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Di(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ys(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let d,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}d=this._selectQuality(h),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${h}`)},s={updateChunk:(d,p)=>{let m=re();if(this.chunkRateEstimator.addInterval(d,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-d,speed:b}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},a=-1/0,u,o=!0,l=()=>{let h=s.get();if(h&&u&&this.autoQuality){if(o&&h>u&&Va(a)<3e4)return;i(h)}o=this.autoQuality};return{updateChunk:(h,d)=>{let p=s.updateChunk(h,d);return p&&l(),p},notifySwitch:h=>{let d=re();h<u&&(a=d),u=h}}}_fetchManifest(e,t,i){this.manifestRequest=ei(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ts).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ee(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let u=[];return a?.length?(a.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Kc))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as ed,filter as Wo,fromEvent as td,interval as id,isHigher as rd,isInvariantQuality as sd,isLower as ad,merge as nd,Subject as qo,Subscription as od}from"@vkontakte/videoplayer-shared/evergreen";var Fa=class{constructor(){this.onDroopedVideoFramesLimit$=new qo;this.subscription=new od;this.playing=!1;this.tracks=[];this.forceChecker$=new qo;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!sd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&rd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(td(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=id(this.droppedFramesChecker.checkTime).pipe(Wo(()=>this.playing),Wo(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(ed(this.droppedFramesChecker.checkTime)),i=nd(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>ad(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ti=Fa;import{map as ud,Observable as ld}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as cd}from"@vkontakte/videoplayer-shared/evergreen";var Vi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var dd=(n,e)=>new ld(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,u)=>{a.forEach(o=>t.next(o.isIntersecting||Vi()))},{...i,...e});r.observe(n);let s=cd(document,"visibilitychange").pipe(ud(a=>!document.hidden||Vi())).subscribe(a=>t.next(a));return()=>{r.unobserve(n),s.unsubscribe()}}),Ve=dd;var vd=["paused","playing","ready"],yd=["paused","playing","ready"],Ci=class{constructor(e){this.subscription=new gd;this.videoState=new C("stopped");this.representations$=new Na([]);this.droppedFramesManager=new ti;this.maxSeekBackTime$=new Na(1/0);this.zeroTime$=new Na(void 0);this.liveOffset=new Pt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Ko.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=ft(r.name)??Sd(r.video),u=r.bitrate/1e3,o={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),_a(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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 a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(yd.includes(e)&&(a||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&vd.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ee(this.params.source.url,o))}return;default:return Go(e)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ko.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Jo(this.videoState.stateChangeStarted$.pipe(Is(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Is(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(ue(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ie(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Is(r=>r.map(({track:s})=>s)),Xo(r=>!!r.length),bd()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(md(),Is(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(hd({zeroTime:this.zeroTime$.pipe(Xo(_a)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(We(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Zo(r),min:s&&Zo(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Go(r.to)}},t)).add(Jo(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,fd(["init"])).pipe(pd(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),ye(this.video)}createLiveDashPlayer(){let e=new Bi({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&_a(t)?t:Ye(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput: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=r?.id,a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==u){let l=e.find(({track:c})=>c.id===s)?.representation;Yo(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Yo(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(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var eu=Ci;var se=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,s=n.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Ih,assertNonNullable as Eh,debounce as xh,ErrorCategory as Cu,filter as un,filterChanged as zs,fromEvent as kh,isNonNullable as Ou,isNullable as wh,map as ln,merge as Ws,observableFrom as cn,once as Fu,Subscription as Ah}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared/evergreen";var Es=n=>{if(!n)return{id:"EmptyResponse",category:Oi.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Oi.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Oi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Oi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Oi.PARSER,message:"Response is valid XML, but parser failed"}};var le=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as Za,assertNonNullable as li,combine as ci,ErrorCategory as Ne,filter as Os,filterChanged as mr,flattenObject as fr,fromEvent as ot,getTraceSubscriptionMethod as sh,interval as en,isNonNullable as br,isNullable as Pu,map as di,merge as Bt,now as tn,Subject as Fs,Subscription as Mu,tap as ah,throttle as nh,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Td,ErrorCategory as tu,Subject as iu}from"@vkontakte/videoplayer-shared/evergreen";var Id=18,ru=!1;try{ru=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=Id}catch(n){console.error(n)}var Ua=class{constructor(e){this.bufferFull$=new iu;this.error$=new iu;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:tu.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ru&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:tu.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:Td(t)}}},su=Ua;var ii=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as St,assertNonNullable as xe,ErrorCategory as st,fromEvent as qa,getExponentialDelay as Ga,isNonNullable as ni,isNullable as ce,now as ws,once as Wd,Subject as qd,Subscription as Gd,ValueSubject as Dt}from"@vkontakte/videoplayer-shared/evergreen";var xs=n=>n.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 ri=class extends Q{};import{assertNever as Ed}from"@vkontakte/videoplayer-shared/evergreen";var Fi=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:Ed(e)}}};var _i=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ni=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var K=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Ui=class extends K{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Hi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qi=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Mt=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var ji=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wi=class extends K{constructor(e,t){if(super(e,t),!this.valid)return;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 qi=class extends K{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Gi=class extends K{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Yi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ki=class extends K{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()}};var Xi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ji=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zi=class extends K{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var er=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var tr=class extends K{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())}};var ir=class extends K{constructor(t,i){super(t,i);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 rr=class extends K{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var sr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ar=class extends K{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var nr=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var kd={ftyp:_i,moov:Ni,mvhd:Ui,moof:Hi,mdat:Qi,sidx:Mt,trak:ji,mdia:Yi,mfhd:Zi,tkhd:Ki,traf:er,tfhd:tr,tfdt:ir,trun:rr,minf:Xi,sv3d:zi,st3d:Wi,prhd:qi,proj:Ji,equi:Gi,uuid:Fi,stbl:sr,stsd:ar,avc1:nr,unknown:ri},rt=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!a||!xs(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=kd[e];return i?new i(t,new n):new ri(t,new n)}};var gt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{xs(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ad=new TextDecoder("ascii"),Ld=n=>Ad.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",$d=n=>{let e=new Mt(n,new rt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,u})},Pd=(n,e)=>{let i=new rt().parse(n),r=new gt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let u=s[0],o=a[a.length-1],l=u.source.byteOffset,h=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(n.buffer,l,h)},Md=n=>{let t=new rt().parse(n),i=new gt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Rd=n=>{let t=new rt().parse(n);return new gt(t).find("sidx")?.timescale},Dd=(n,e)=>{let i=new rt().parse(n),s=new gt(i).findAll("traf"),a=s[s.length-1].children.find(h=>h.type==="tfhd"),u=s[s.length-1].children.find(h=>h.type==="tfdt"),o=s[s.length-1].children.find(h=>h.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((h,d)=>h+d,0):l=a.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},Bd=n=>{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}}},i=new rt().parse(n),r=new gt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},au={validateData:Ld,parseInit:Bd,getIndexRange:()=>{},parseSegments:$d,parseFeedableSegmentChunk:Pd,getChunkEndTime:Dd,getServerLatencyTimestamps:Md,getTimescaleFromIndex:Rd};import{assertNonNullable as Ha,isNonNullable as lu,isNullable as Cd}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Vd}from"@vkontakte/videoplayer-shared/evergreen";var nu={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"}},ou=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ur(n,t),r=i in nu,s=r?nu[i].type:"binary",a=n.getUint8(t),u=0;a&128?u=1:a&64?u=2:a&32?u=3:a&16?u=4:a&8?u=5:a&4?u=6:a&2?u=7:a&1&&(u=8);let o=new DataView(n.buffer,n.byteOffset+t+1,u-1),l=a&255>>u,c=ur(o),h=l*2**((u-1)*8)+c,d=t+u,p;return d+h>n.byteLength?p=new DataView(n.buffer,n.byteOffset+d):p=new DataView(n.buffer,n.byteOffset+d,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+h,value:p,valueSize:h}},ur=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ur(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:Vd(e)}},Rt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=ou(i);if(!e(r))return;r.type==="master"&&Rt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},uu=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=ou(n);return Rt(r.value,({tag:s,type:a,value:u})=>(s===17143?e=Fe(u,a):s===17026?t=Fe(u,a):s===17029&&(i=Fe(u,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var cu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Od=[231,22612,22743,167,171,163,160,175],Fd=n=>{let e,t,i,r,s=!1,a=!1,u=!1,o,l,c=!1,h=0;return Rt(n,({tag:d,type:p,value:m,valueSize:f})=>{if(d===21419){let b=Fe(m,p);l=ur(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=Fe(m,p):d===17545?r=Fe(m,p):d===21420&&l===475249515?o=Fe(m,p):d===374648427?Rt(m,({tag:b,type:g,value:x})=>b===30321?(c=Fe(x,g)===1,!1):!0):s&&a&&cu.includes(d)&&(u=!0),!u}),Ha(e,"Failed to parse webm Segment start"),Ha(t,"Failed to parse webm Segment end"),Ha(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:c,stereoMode:h,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},_d=n=>{if(Cd(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Nd=(n,e)=>{let t=!1,i=!1,r=u=>lu(u.time)&&lu(u.position),s=[],a;return Rt(n,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Fe(l,o));break;case 183:break;case 241:a&&(a.position=Fe(l,o));break;default:t&&cu.includes(u)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((u,o)=>{let{time:l,position:c}=u,h=s[o+1];return{status:"none",time:{from:l,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Ud=n=>{let e=0,t=!1;try{Rt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Od.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},du={validateData:uu,parseInit:Fd,getIndexRange:_d,parseSegments:Nd,parseFeedableSegmentChunk:Ud};var Ke=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return du;case"mp4":return au}}throw new ReferenceError(`Unsupported mime type ${n}`)};var Xe=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Qa=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),u=s+a;return["6E","7A","F4"].includes(u)}}return!1};import{isNonNullable as Qd,isNullable as mu}from"@vkontakte/videoplayer-shared/evergreen";var hu=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var pu=n=>{try{let e=Hd(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(u=>{let o=a[u];(typeof o>"u"||o==="")&&delete a[u]}),a}return null}catch{return null}};function Hd(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
117
117
  (?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
118
118
  (-(?<script>[a-z]{4}))?
119
119
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
120
120
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
121
121
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
122
122
  (?:-(?<privateuse>(?:${e})))?
123
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}import{videoSizeToQuality as Dp}from"@vkontakte/videoplayer-shared/evergreen";var el=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let o=(s?Ft(s):void 0)??Dp({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},tl=({id:n,bitrate:e})=>({id:n,bitrate:e}),il=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),rl=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Pn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Mn=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Ln=n=>"url"in n,De=n=>n.type==="template",kr=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var al=n=>{if(!n?.startsWith("P"))return;let e=(a,o)=>{let u=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(o,u)=>sl(s)?o:sl(u)?s:s.padStart(parseInt(u,10),"0"))}return t},nl=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,x=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((w,g)=>({...w,[g.id]:g.children}),{}),E=v.reduce((w,g)=>({...w,[g.id]:g.getAttribute("duration")}),{});x?S=al(x):Object.values(E).filter(w=>w).length&&!u?S=Object.values(E).reduce((w,g)=>w+(al(g)??0),0):f&&(S=parseInt(f,10));let L=0,V=s.getAttribute("profiles")?.split(",")??[];for(let w of v.map(g=>g.id))for(let g of I[w]){let R=g.getAttribute("id")??"id"+(L++).toString(10),y=g.getAttribute("mimeType")??"",T=g.getAttribute("codecs")??"",A=g.getAttribute("contentType")??y?.split("/")[0],ee=g.getAttribute("profiles")?.split(",")??[],$=Zu(g.getAttribute("lang")??"")??{},N=g.querySelector("Label")?.textContent?.trim()??void 0,Y=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),he=g.querySelector("Role")?.getAttribute("value")??void 0,se=A,X={id:R,language:$.language,isDefault:he==="main",label:N,codecs:T,hdr:se==="video"&&xi(T),mime:y,representations:[]};for(let M of Y){let D=M.getAttribute("lang")??void 0,Se=N??g.getAttribute("label")??M.getAttribute("label")??void 0,me=M.querySelector("BaseURL")?.textContent?.trim()??"",J=new URL(me||o,e).toString(),fe=M.getAttribute("mimeType")??y,ze=M.getAttribute("codecs")??T??"",Pe;if(A==="text"){let oe=M.getAttribute("id")||"",Qe=$.privateuse?.includes("x-auto")||oe.includes("_auto"),ge=M.querySelector("SegmentTemplate");if(ge){let rt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},bt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(ge.getAttribute("startNumber")??"",10)??1,We=parseInt(ge.getAttribute("timescale")??"",10),Yt=ge.querySelectorAll("SegmentTimeline S")??[],qe=ge.getAttribute("media");if(!qe)continue;let St=[],vt=0,yt="",Ge=0,st=gt,W=0;for(let ae of Yt){let Me=parseInt(ae.getAttribute("d")??"",10),Z=parseInt(ae.getAttribute("r")??"",10)||0,ve=parseInt(ae.getAttribute("t")??"",10);W=Number.isFinite(ve)?ve:W;let Le=Me/We*1e3,Ye=W/We*1e3;for(let ce=0;ce<Z+1;ce++){let ye=Pt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:(W+ce*Me).toString(10)}),Ke=(Ye??0)+ce*Le,nt=Ke+Le;st++,St.push({time:{from:Ke,to:nt},url:ye})}W+=(Z+1)*Me,vt+=(Z+1)*Le}Ge=W/We*1e3,yt=Pt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:W.toString(10)});let at={time:{from:Ge,to:1/0},url:yt},be={type:"template",baseUrl:J,segmentTemplateUrl:qe,initUrl:"",totalSegmentsDurationMs:vt,segments:St,nextSegmentBeyondManifest:at,timescale:We};Pe={id:oe,kind:"text",segmentReference:be,profiles:[],duration:S,bitrate:bt,mime:"",codecs:"",width:0,height:0,isAuto:Qe}}else Pe={id:oe,isAuto:Qe,kind:"text",url:J}}else{let oe=M.getAttribute("contentType")??fe?.split("/")[0]??A,Qe=g.getAttribute("profiles")?.split(",")??[],ge=parseInt(M.getAttribute("width")??"",10),rt=parseInt(M.getAttribute("height")??"",10),bt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,gt=M.getAttribute("frameRate")??"",We=M.getAttribute("quality")??void 0,Yt=gt?aa(gt):void 0,qe=M.getAttribute("id")??"id"+(L++).toString(10),St=oe==="video"?`${rt}p`:oe==="audio"?`${bt}Kbps`:ze,vt=`${qe}@${St}`,yt=[...V,...ee,...Qe],Ge,st=M.querySelector("SegmentBase"),W=M.querySelector("SegmentTemplate")??re;if(st){let be=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ae,Me]=be.split("-").map(ye=>parseInt(ye,10)),Z={from:ae,to:Me},ve=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Le,Ye]=ve?ve.split("-").map(ye=>parseInt(ye,10)):[],ce=ve?{from:Le,to:Ye}:void 0;Ge={type:"byteRange",url:J,initRange:Z,indexRange:ce}}else if(W){let be={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},ae=parseInt(W.getAttribute("timescale")??"",10),Me=W.getAttribute("initialization")??"",Z=W.getAttribute("media"),ve=parseInt(W.getAttribute("startNumber")??"",10)??1,Le=Pt(Me,be);if(!Z)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=W.querySelectorAll("SegmentTimeline S")??[],ce=[],ye=0,Ke="",nt=0;if(Ye.length){let Tt=ve,ne=0;for(let Xe of Ye){let de=parseInt(Xe.getAttribute("d")??"",10),Be=parseInt(Xe.getAttribute("r")??"",10)||0,It=parseInt(Xe.getAttribute("t")??"",10);ne=Number.isFinite(It)?It:ne;let Kt=de/ae*1e3,Ja=ne/ae*1e3;for(let xt=0;xt<Be+1;xt++){let Za=Pt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:(ne+xt*de).toString(10)}),Fi=(Ja??0)+xt*Kt,en=Fi+Kt;Tt++,ce.push({time:{from:Fi,to:en},url:Za})}ne+=(Be+1)*de,ye+=(Be+1)*Kt}nt=ne/ae*1e3,Ke=Pt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:ne.toString(10)})}else if(Vp(S)){let ne=parseInt(W.getAttribute("duration")??"",10)/ae*1e3,Xe=Math.ceil(S/ne),de=0;for(let Be=1;Be<Xe;Be++){let It=Pt(Z,{...be,segmentNumber:Be.toString(10),segmentTime:de.toString(10)});ce.push({time:{from:de,to:de+ne},url:It}),de+=ne}nt=de,Ke=Pt(Z,{...be,segmentNumber:Xe.toString(10),segmentTime:de.toString(10)})}let Xa={time:{from:nt,to:1/0},url:Ke};Ge={type:"template",baseUrl:J,segmentTemplateUrl:Z,initUrl:Le,totalSegmentsDurationMs:ye,segments:ce,nextSegmentBeyondManifest:Xa,timescale:ae}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!fe)continue;let at={video:"video",audio:"audio",text:"text"}[oe];if(!at)continue;se||=at,Pe={id:vt,kind:at,segmentReference:Ge,profiles:yt,duration:S,bitrate:bt,mime:fe,codecs:ze,width:ge,height:rt,fps:Yt,quality:We}}X.language||=D,X.label||=Se,X.mime||=fe,X.codecs||=ze,X.hdr||=se==="video"&&xi(ze),X.representations.push(Pe)}if(se){let M=r[se].find(D=>D.id===X.id);if(M&&X.representations.every(D=>De(D.segmentReference)))for(let D of M.representations){let me=X.representations.find(fe=>fe.id===D.id)?.segmentReference,J=D.segmentReference;J.segments.push(...me.segments),J.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[se].push(X)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{isNonNullable as ol}from"@vkontakte/videoplayer-shared/evergreen";var C=(n,e)=>ol(n)&&ol(e)&&n.readyState==="open"&&Cp(n,e);function Cp(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var wr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ii(0);this.currentLowLatencySegmentLength$=new ii(0);this.currentSegmentLength$=new ii(0);this.onLastSegment$=new ii(!1);this.fullyBuffered$=new ii(!1);this.playingRepresentation$=new ii(void 0);this.playingRepresentationInit$=new ii(void 0);this.error$=new Fp;this.gaps=[];this.subscription=new _p;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qu(this.sourceBuffer),this.subscription.add($n(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),o??={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(o)})),this.subscription.add($n(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,a*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Ei(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Ei(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ut(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!De(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r);let s=this.segments.get(i);He(s,"No segments for starting representation");let a=this.initData.get(i);if(He(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);He(s,`No such representation ${i}`);let a=this.segments.get(i),o=this.initData.get(i);if(we(o)||we(a)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),a=this.segments.get(i),He(a,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ei(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!we(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(we(e)||we(this.downloadingRepresentationId)||we(this.playingRepresentationId)||we(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);Ei(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&Ti(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))p="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Ei(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!De(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],o=a.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!De(r))return;let s=this.segments.get(i.id)??[],a=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Pt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,S=h>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+x||r<x&&m-h>=x||m<=i+x;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(ke(this.sourceBuffer.buffered,h)&&ke(this.sourceBuffer.buffered,m)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(o<=p||u<=c);d++){let h=a[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){De(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ut(o,async function*(){let p=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(a,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=na(),!p)return;let c=new DataView(p),d=Er(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),kr(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())De(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Ut(a,async function*(){let u=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),$n(window,"online").pipe(Op()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:a,priority:i}),this.lastDataObtainedTimestampMs=na(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),kr(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(De(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=na(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!De(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=na();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Er(a.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await a();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let f=Er(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?b:f.parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(we(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ke(this.sourceBuffer.buffered,e.segment.time.from,100)&&ke(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ln(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?Ut(this.destroyAbortController.signal,async function*(){let o=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Er(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&De(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||we(e))return!1;let r=[],s=0,a=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(s>=t)return r;r.push({...u.time}),r=a(r);let l=Ln(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||we(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(we(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||we(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=a&&p.to+t>=o),l=e.filter(p=>a>=p.from&&a<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ht=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var oa=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as Ar,assertNever as ul,fromEvent as ll,merge as Np,now as Pr,Subscription as Up,Subject as cl,ValueSubject as Dn,flattenObject as ki,ErrorCategory as Mr}from"@vkontakte/videoplayer-shared/evergreen";var ua=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ca=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Dn(void 0);this.lastConnectionReused$=new Dn(void 0);this.lastRequestFirstBytes$=new Dn(void 0);this.recoverableError$=new cl;this.error$=new cl;this.abortAllController=new AbortController;this.subscription=new Up;this.fetchManifest=Ar(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ht(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ua(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(la);return r?(t.log("success",ki({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ki({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ar(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:ul(t)}this.requestQuic&&(l=Ht(l));let d=this.abortAllController.signal,h;if(a){let R=new AbortController;if(h=Np(ll(this.abortAllController.signal,"abort"),ll(a,"abort")).subscribe(()=>{try{R.abort()}catch(y){la(y)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{R.abort()}catch(y){la(y)}d=R.signal}let m=Pr();c.log("startRequest",ki({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:p,signal:d}),b=Pr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){h?.unsubscribe();let R=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:R}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let R=Pr(),y={requestStartedAt:m,requestEndedAt:R,duration:R-m};return c.log("endRequest",ki(y)),c.end(),f.arrayBuffer()}let[S,x]=f.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(x,u);let I=0,E=new Uint8Array(0),L=!1,V=R=>{h?.unsubscribe(),L=!0,la(R)},k=Ar(d,async function*({done:R,value:y}){if(I===0&&this.lastRequestFirstBytes$.next(Pr()-m),d.aborted){h?.unsubscribe();return}if(!R&&y){let T=new Uint8Array(E.length+y.length);T.set(E),T.set(y,E.length),E=T,I+=y.byteLength,r?.(new DataView(E.buffer),I),yield v?.read().then(k,V)}}.bind(this));yield v?.read().then(k,V),h?.unsubscribe();let w=Pr(),g={failed:L,requestStartedAt:m,requestEndedAt:w,duration:w-m};return L?(c.error("endRequest",ki(g)),c.end(),null):(c.log("endRequest",ki(g)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ar(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,o=s,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),o=Math.max(p,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-a,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ar(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:ul(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Mr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Mr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Mr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Mr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Mr.FATAL})}}},la=n=>{if(!kr(n))throw n};var Lt=(n,e,t)=>t*e+(1-t)*n,Vn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,dl=(n,e,t,i)=>{let r=0,s=t,a=Vn(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===o};import{isNullable as Hp,ValueSubject as pl}from"@vkontakte/videoplayer-shared/evergreen";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new pl(e.initial),this.debounced$=new pl(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(Hp(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 da=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Lt(this.slow,e,this.params.emaAlphaSlow),this.fast=Lt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var pa=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Lt(this.emaSmoothed,e,this.params.emaAlpha);let i=dl(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ha=class extends jt{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?Lt(this.smoothed,t,this.params.emaAlpha):t}};var Bt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new da({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new pa({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new ha({initial:e,label:"liveEdgeDelay",...t})}};var wi=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as jp,ValueSubject as zp}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class n{constructor(e,t){this.currentRepresentation$=new zp(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!jp(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<a||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&De(t.segmentReference))}};import{assertNever as fa}from"@vkontakte/videoplayer-shared/evergreen";var hl=(n,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:a}=O.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return n.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return a;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return fa(l)}})},ma=n=>{let{webmDecodingInfo:e}=O.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:fa(n)}return[t,i]},ml=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ma(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(O.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...ma(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ma(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ma(n),...r,"HLS","HLS_ONDEMAND"];default:fa(e)}return O.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},fl=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],o,u=O.device.isMac&&O.browser.isSafari;if(O.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=a;break}default:fa(n)}else O.video.nativeHlsSupported&&!u?o=a:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Cn=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ba=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)};var Jp=["timeupdate","progress","play","seeked","stalled","waiting"],Zp=["timeupdate","progress","loadeddata","playing","seeked"];var va=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Sl;this.representationSubscription=new Sl;this.state$=new _("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentAudioRepresentation$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new Sa;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.currentLiveTextRepresentation$=new ue(null);this.isLive$=new ue(!1);this.isActiveLive$=new ue(!1);this.isLowLatency$=new ue(!1);this.liveDuration$=new ue(0);this.liveSeekableDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(0);this.liveStreamStatus$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLatency$=new ue(void 0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.currentStallDuration$=new ue(0);this.videoLastDataObtainedTimestamp$=new ue(0);this.fetcherRecoverableError$=new Sa;this.fetcherError$=new Sa;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Sa;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Fn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Fn(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=nl(e??"",this.manifestUrlString)}catch(a){let o=sa(e)??{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(o)}if(!t)return null;let i=(a,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let u=t.streams[a].filter(({mime:c,codecs:d})=>i(a,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=ba(l);if(p&&(r[a]=u.filter(({codecs:c})=>c.startsWith(p))),a==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);O.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",$r(s)),s}.bind(this));this.initRepresentations=Fn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",$r({initialVideo:e,initialAudio:t,sourceHls:i})),Ai(this.manifest),Ai(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add($t(d,"error").pipe(ga(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new wr("video",this.source,o,a),this.bufferManagers=[this.videoBufferManager],Rr(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new wr("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}Lr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Lr(this.manifest.streams.text,a)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ri(...Zp.map(d=>$t(this.element,d))).pipe(Mi(d=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),Br(),Kp(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ri($t(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Br()).subscribe(h=>this.liveStreamEndTimestamp=Nn())),this.subscription.add($t(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=_n(1e3).subscribe(h=>{let m=Ct(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add($t(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Pi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mi(({isActiveLive:h,isLowLatency:m})=>h&&m),Br()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||wi(this.element,1)})),this.representationSubscription.add(Pi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ga(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Pi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ga(({isLive:h})=>h),Br((h,m)=>m.bufferLength<h.bufferLength),Mi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=Ct(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Pi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>S&&(I=1+Math.sign(v)*x),wi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(Pi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xp(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=Ct(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(V);let k="none";if(L?k="active_low_latency":this.isLowLatency$.getValue()&&V?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),k==="live_forward_buffering"||k==="live_with_target_offset"){let w=d-(x+v),g=this.normolizeLiveOffset(Math.trunc(b+w/f)),R=Math.abs(g-b),y=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?y=b:g>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(y=g),this.manifestUrlString=pe(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ri(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Mi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ri(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Mi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Pi({allBuffersFull:l,someBufferEnded:p}).pipe(Br(),Mi(({allBuffersFull:d,someBufferEnded:h})=>d&&h),ga(d=>d));if(this.representationSubscription.add(ri(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ri(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),De(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Rr(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=_n(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ca({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Ai(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Nn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=pe(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ai(this.element),this.state$.setState("running"),this.subscription.add(ri(...Jp.map(e=>$t(this.element,e)),$t(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add($t(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add($t(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ke(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Nn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,p=u<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",$r(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=_n(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ai(this.element),Ai(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ke(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(gl(this.element)||gl(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",$r({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Rr(this.element)&&Rr(this.source)&&Rr(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Yp(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-a<=r&&u.to+a>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",$r(i)))}}};var ya=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ta=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,a=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:a},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var yl=`attribute vec2 a_vertex;
123
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var fu=n=>{if(!n?.startsWith("P"))return;let e=(a,u)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(u,o)=>mu(s)?u:mu(o)?s:s.padStart(parseInt(o,10),"0"))}return t},ks=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map($=>$.textContent?.trim()??""),u=a.at(0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),h=s.getElementsByTagName("vk:Attrs")[0],d=h?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=h?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=h?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=h?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,x=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce(($,y)=>({...$,[y.id]:y.children}),{}),k=v.reduce(($,y)=>({...$,[y.id]:y.getAttribute("duration")}),{});x?g=fu(x):Object.values(k).filter($=>$).length&&!o?g=Object.values(k).reduce(($,y)=>$+(fu(y)??0),0):f&&(g=parseInt(f,10));let L=0,P=s.getAttribute("profiles")?.split(",")??[];for(let $ of v.map(y=>y.id))for(let y of I[$]){let O=y.getAttribute("id")??"id"+(L++).toString(10),M=y.getAttribute("mimeType")??"",S=y.getAttribute("codecs")??"",T=y.getAttribute("contentType")??M?.split("/")[0],z=y.getAttribute("profiles")?.split(",")??[],R=pu(y.getAttribute("lang")??"")??{},N=y.querySelector("Label")?.textContent?.trim()??void 0,Y=y.querySelectorAll("Representation"),Z=y.querySelector("SegmentTemplate"),te=y.querySelector("Role")?.getAttribute("value")??void 0,ne=T,oe={id:O,language:R.language,isDefault:te==="main",label:N,codecs:S,hdr:ne==="video"&&Qa(S),mime:M,representations:[]};for(let H of Y){let F=H.getAttribute("lang")??void 0,ge=N??y.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(he||u,e).toString(),Me=H.getAttribute("mimeType")??M,lt=H.getAttribute("codecs")??S??"",He;if(T==="text"){let we=H.getAttribute("id")||"",ct=R.privateuse?.includes("x-auto")||we.includes("_auto"),Qe=H.querySelector("SegmentTemplate");if(Qe){let vi={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Fr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,_r=parseInt(Qe.getAttribute("startNumber")??"",10)??1,Ut=parseInt(Qe.getAttribute("timescale")??"",10),ga=Qe.querySelectorAll("SegmentTimeline S")??[],Ht=Qe.getAttribute("media");if(!Ht)continue;let Nr=[],Ur=0,Hr="",Qt=0,yi=_r,pe=0;for(let Ce of ga){let kt=parseInt(Ce.getAttribute("d")??"",10),Re=parseInt(Ce.getAttribute("r")??"",10)||0,dt=parseInt(Ce.getAttribute("t")??"",10);pe=Number.isFinite(dt)?dt:pe;let wt=kt/Ut*1e3,jt=pe/Ut*1e3;for(let je=0;je<Re+1;je++){let ht=_e(Ht,{...vi,segmentNumber:yi.toString(10),segmentTime:(pe+je*kt).toString(10)}),zt=(jt??0)+je*wt,Ii=zt+wt;yi++,Nr.push({time:{from:zt,to:Ii},url:ht})}pe+=(Re+1)*kt,Ur+=(Re+1)*wt}Qt=pe/Ut*1e3,Hr=_e(Ht,{...vi,segmentNumber:yi.toString(10),segmentTime:pe.toString(10)});let Ti={time:{from:Qt,to:1/0},url:Hr},Ze={type:"template",baseUrl:ie,segmentTemplateUrl:Ht,initUrl:"",totalSegmentsDurationMs:Ur,segments:Nr,nextSegmentBeyondManifest:Ti,timescale:Ut};He={id:we,kind:"text",segmentReference:Ze,profiles:[],duration:g,bitrate:Fr,mime:"",codecs:"",width:0,height:0,isAuto:ct}}else He={id:we,isAuto:ct,kind:"text",url:ie}}else{let we=H.getAttribute("contentType")??Me?.split("/")[0]??T,ct=y.getAttribute("profiles")?.split(",")??[],Qe=parseInt(H.getAttribute("width")??"",10),vi=parseInt(H.getAttribute("height")??"",10),Fr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,_r=H.getAttribute("frameRate")??"",Ut=H.getAttribute("quality")??void 0,ga=_r?hu(_r):void 0,Ht=H.getAttribute("id")??"id"+(L++).toString(10),Nr=we==="video"?`${vi}p`:we==="audio"?`${Fr}Kbps`:lt,Ur=`${Ht}@${Nr}`,Hr=[...P,...z,...ct],Qt,yi=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(yi){let Ze=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ce,kt]=Ze.split("-").map(ht=>parseInt(ht,10)),Re={from:Ce,to:kt},dt=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[wt,jt]=dt?dt.split("-").map(ht=>parseInt(ht,10)):[],je=dt?{from:wt,to:jt}:void 0;Qt={type:"byteRange",url:ie,initRange:Re,indexRange:je}}else if(pe){let Ze={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ce=parseInt(pe.getAttribute("timescale")??"",10),kt=pe.getAttribute("initialization")??"",Re=pe.getAttribute("media"),dt=parseInt(pe.getAttribute("startNumber")??"",10)??1,wt=_e(kt,Ze);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=pe.querySelectorAll("SegmentTimeline S")??[],je=[],ht=0,zt="",Ii=0;if(jt.length){let Qr=dt,Oe=0;for(let Wt of jt){let ze=parseInt(Wt.getAttribute("d")??"",10),At=parseInt(Wt.getAttribute("r")??"",10)||0,jr=parseInt(Wt.getAttribute("t")??"",10);Oe=Number.isFinite(jr)?jr:Oe;let Sa=ze/Ce*1e3,Jl=Oe/Ce*1e3;for(let zr=0;zr<At+1;zr++){let Zl=_e(Re,{...Ze,segmentNumber:Qr.toString(10),segmentTime:(Oe+zr*ze).toString(10)}),Gn=(Jl??0)+zr*Sa,ec=Gn+Sa;Qr++,je.push({time:{from:Gn,to:ec},url:Zl})}Oe+=(At+1)*ze,ht+=(At+1)*Sa}Ii=Oe/Ce*1e3,zt=_e(Re,{...Ze,segmentNumber:Qr.toString(10),segmentTime:Oe.toString(10)})}else if(Qd(g)){let Oe=parseInt(pe.getAttribute("duration")??"",10)/Ce*1e3,Wt=Math.ceil(g/Oe),ze=0;for(let At=1;At<Wt;At++){let jr=_e(Re,{...Ze,segmentNumber:At.toString(10),segmentTime:ze.toString(10)});je.push({time:{from:ze,to:ze+Oe},url:jr}),ze+=Oe}Ii=ze,zt=_e(Re,{...Ze,segmentNumber:Wt.toString(10),segmentTime:ze.toString(10)})}let Xl={time:{from:Ii,to:1/0},url:zt};Qt={type:"template",baseUrl:ie,segmentTemplateUrl:Re,initUrl:wt,totalSegmentsDurationMs:ht,segments:je,nextSegmentBeyondManifest:Xl,timescale:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!we||!Me)continue;let Ti={video:"video",audio:"audio",text:"text"}[we];if(!Ti)continue;ne||=Ti,He={id:Ur,kind:Ti,segmentReference:Qt,profiles:Hr,duration:g,bitrate:Fr,mime:Me,codecs:lt,width:Qe,height:vi,fps:ga,quality:Ut}}oe.language||=F,oe.label||=ge,oe.mime||=Me,oe.codecs||=lt,oe.hdr||=ne==="video"&&Qa(lt),oe.representations.push(He)}if(ne){let H=r[ne].find(F=>F.id===oe.id);if(H&&oe.representations.every(F=>F.segmentReference.type==="template"))for(let F of H.representations){let he=oe.representations.find(Me=>Me.id===F.id)?.segmentReference,ie=F.segmentReference;ie.segments.push(...he.segments),ie.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ne].push(oe)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as jd}from"@vkontakte/videoplayer-shared/evergreen";var bu=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??jd({width:e,height:t});return u&&{id:n,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},gu=({id:n,bitrate:e})=>({id:n,bitrate:e}),Su=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),vu=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),ja=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),za=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Wa=n=>"url"in n,Le=n=>n.type==="template";import{isNonNullable as yu}from"@vkontakte/videoplayer-shared/evergreen";var D=(n,e)=>yu(n)&&yu(e)&&n.readyState==="open"&&zd(n,e);function zd(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var lr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Dt(0);this.currentLowLatencySegmentLength$=new Dt(0);this.currentSegmentLength$=new Dt(0);this.onLastSegment$=new Dt(!1);this.fullyBuffered$=new Dt(!1);this.playingRepresentation$=new Dt(void 0);this.playingRepresentationInit$=new Dt(void 0);this.error$=new qd;this.gaps=[];this.subscription=new Gd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=St(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new su(this.sourceBuffer),this.subscription.add(qa(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),u??={id:"SegmentEjection",category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(u)})),this.subscription.add(qa(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:st.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!D(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,ii(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,l<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=St(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();ni(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=St(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();ni(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=St(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!Le(c.segmentReference))return;let h=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,h)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let s=this.segments.get(i);xe(s,"No segments for starting representation");let a=this.initData.get(i);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,St(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);xe(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(ce(u)||ce(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),xe(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();ni(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ce(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ni(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);ni(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),h=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+a&&(s=h)}if(isFinite(this.bufferLimit)&&ii(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let h=o.at(0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ni(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Le(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Le(r))return;let s=this.segments.get(i.id)??[],a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+x||r<x&&m-p>=x||m<=i+x;return(d==="none"||d==="partially_ejected"&&g&&v&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(le(this.sourceBuffer.buffered,p)&&le(this.sourceBuffer.buffered,m)))&&g&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(u<=c||o<=h);d++){let p=a[d];if(u+=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,i="auto"){Le(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await St(u,async function*(){let c=Ga(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ws(),!c)return;let h=new DataView(c),d=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(h,f)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(h);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Xe(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Le(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await St(a,async function*(){let o=Ga(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),qa(window,"online").pipe(Wd()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ws(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Xe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Le(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ws(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ws();let h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Ke(a.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let c=l.byte.from-i,h=l.byte.to-i,d=h-c+1,p=c<r,m=h<=r;if(!p)continue;let f=Ke(u.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===d?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(le(this.sourceBuffer.buffered,e.segment.time.from,100)&&le(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:st.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Wa(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?St(this.destroyAbortController.signal,async function*(){let u=Ga(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,h=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,h);let d=c;this.isLive&&Le(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:st.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ce(e))return!1;let r=[],s=0,a=o=>{o.sort((c,h)=>c.from-h.from);let l=[o[0]];for(let c=1;c<o.length;c++){let{from:h,to:d}=o[c],p=l[l.length-1];p.to>=h?p.to=Math.max(p.to,d):l.push(o[c])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let l=Wa(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||h)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,c=this.sourceBuffer.buffered.end(o)*1e3,h=0;for(let d of this.segments.values())for(let p of d)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&h++;if(h===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+o&&c.status==="fed"&&u(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ce(e)?0:se(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:st.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ce(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(c=>c.from-t<=a&&c.to+t>=u),l=e.filter(c=>a>=c.from&&a<c.to-t||u>c.from+t&&u<=c.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:st.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var vt=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var As=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as cr,assertNever as Tu,fromEvent as Iu,merge as Yd,now as dr,Subscription as Kd,Subject as Eu,ValueSubject as Ya,flattenObject as oi,ErrorCategory as hr}from"@vkontakte/videoplayer-shared/evergreen";var Ls=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ps=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ya(void 0);this.lastConnectionReused$=new Ya(void 0);this.lastRequestFirstBytes$=new Ya(void 0);this.recoverableError$=new Eu;this.error$=new Eu;this.abortAllController=new AbortController;this.subscription=new Kd;this.fetchManifest=cr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ls(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch($s);return r?(t.log("success",oi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",oi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=cr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,h=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(c,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),c=S.toString();break}default:Tu(t)}this.requestQuic&&(c=vt(c));let p=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=Yd(Iu(this.abortAllController.signal,"abort"),Iu(a,"abort")).subscribe(()=>{try{S.abort()}catch(T){$s(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(T){$s(T)}p=S.signal}let f=dr();d.log("startRequest",oi({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:f}));let b=yield this.doFetch(c,{priority:s,headers:h,signal:p}),g=dr();if(!b)return d.error("error",{message:"No response in request"}),d.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){m?.unsubscribe();let S=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:S}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!u){m?.unsubscribe();let S=dr(),T={requestStartedAt:f,requestEndedAt:S,duration:S-f};return d.log("endRequest",oi(T)),d.end(),b.arrayBuffer()}let x=b.body;if(u){let S;[x,S]=b.body.tee(),this.throughputEstimator?.trackStream(S,o)}let v=x.getReader(),I,k=parseInt(b.headers.get("content-length")??"",10);Number.isFinite(k)&&(I=k),!I&&i&&(I=i.to-i.from+1);let L=0,P=I?new Uint8Array(I):new Uint8Array(0),E=!1,$=S=>{m?.unsubscribe(),E=!0,$s(S)},y=cr(p,async function*({done:S,value:T}){if(L===0&&this.lastRequestFirstBytes$.next(dr()-f),p.aborted){m?.unsubscribe();return}if(!S&&T){if(l&&I)P.set(T,L),L+=T.byteLength;else{let z=new Uint8Array(P.length+T.length);z.set(P),z.set(T,P.length),P=z,L+=T.byteLength}r?.(new DataView(P.buffer),L),yield v?.read().then(y,$)}}.bind(this));yield v?.read().then(y,$),m?.unsubscribe();let O=dr(),M={failed:E,requestStartedAt:f,requestEndedAt:O,duration:O-f};return E?(d.error("endRequest",oi(M)),d.end(),null):(d.log("endRequest",oi(M)),d.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=cr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(a=Math.min(l,r),u=Math.max(c,s))),a=Math.min(a,0);let h=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!h)return null;let d=new DataView(h,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let p=t.parseInit(d),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(h,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(h),segments:b}}.bind(this));this.fetchTemplateRepresentation=cr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=As(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Tu(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:hr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:hr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:hr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:hr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:hr.FATAL})}}},$s=n=>{if(!Xe(n))throw n};var at=(n,e,t)=>t*e+(1-t)*n,Ka=(n,e)=>n.reduce((t,i)=>t+i,0)/e,xu=(n,e,t,i)=>{let r=0,s=t,a=Ka(n,e),u=e<i?e:i;for(let o=0;o<u;o++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===u};import{isNullable as Xd,ValueSubject as ku}from"@vkontakte/videoplayer-shared/evergreen";var yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ku(e.initial),this.debounced$=new ku(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(Xd(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 Ms=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=at(this.slow,e,this.params.emaAlphaSlow),this.fast=at(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Rs=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ka(this.pastMeasures,this.takenMeasures);this.emaSmoothed=at(this.emaSmoothed,e,this.params.emaAlpha);let i=xu(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ds=class extends yt{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?at(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ms({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Rs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ds({initial:e,label:"liveEdgeDelay",...t})}};var ui=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as Jd,ValueSubject as Zd}from"@vkontakte/videoplayer-shared/evergreen";var pr=class n{constructor(e,t){this.currentRepresentation$=new Zd(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Jd(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Le(t.segmentReference))}};import{assertNever as Vs}from"@vkontakte/videoplayer-shared/evergreen";var wu=(n,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:a}=B.video,u=(s.h264||s.h265)&&s.aac,o=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return n.filter(l=>{switch(l){case"DASH_SEP":return o&&i.mp4&&u;case"DASH_WEBM":return o&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return o&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return o&&(i.mp4&&u||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return o&&i.mp4&&u;case"DASH_LIVE_CMAF":return o&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return o&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return a;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return Vs(l)}})},Bs=n=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Vs(n)}return[t,i]},Au=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Bs(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Bs(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Bs(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Bs(n),...r,"HLS","HLS_ONDEMAND"];default:Vs(e)}return B.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Lu=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],u,o=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=a;break}default:Vs(n)}else B.video.nativeHlsSupported&&!o?u=a:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Xa=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Cs=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)};var oh=["timeupdate","progress","play","seeked","stalled","waiting"],uh=["timeupdate","progress","loadeddata","playing","seeked"];var _s=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Mu;this.representationSubscription=new Mu;this.state$=new C("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Fs;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Fs;this.fetcherError$=new Fs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Fs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Za(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Za(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ne.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=ks(e??"",this.manifestUrlString)}catch(a){let u=Es(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(u)}if(!t)return null;let i=(a,u,o)=>!!(this.element?.canPlayType?.(u)&&Ae()?.isTypeSupported?.(`${u}; codecs="${o}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:u,streamIsUnpublished:o,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((u-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";l||(h=o?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let o=t.streams[a].filter(({mime:h,codecs:d})=>i(a,h,d)),l=new Set(o.map(({codecs:h})=>h)),c=Cs(l);if(c&&(r[a]=o.filter(({codecs:h})=>h.startsWith(c))),a==="video"){let h=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),p=r.video.some(m=>!m.hdr);B.display.isHDR&&h&&d?r.video=r.video.filter(m=>m.hdr):p&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",fr(s)),s}.bind(this));this.initRepresentations=Za(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",fr({initialVideo:e,initialAudio:t,sourceHls:i})),li(this.manifest),li(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(ot(d,"error").pipe(Os(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?ts():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Yt())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new lr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],br(t)){let d=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new lr("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}pr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new pr(this.manifest.streams.text,a)),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$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Bt(...uh.map(d=>ot(this.element,d))).pipe(di(d=>this.element?se(this.element.buffered,this.element.currentTime*1e3):0),mr(),ah(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Bt(ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(mr()).subscribe(p=>this.liveStreamEndTimestamp=tn())),this.subscription.add(ot(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=en(1e3).subscribe(p=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ot(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ci({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(di(({isActiveLive:p,isLowLatency:m})=>p&&m),mr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||ui(this.element,1)})),this.representationSubscription.add(ci({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Os(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Os(({isLive:p})=>p),mr((p,m)=>m.bufferLength<p.bufferLength),di(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>g&&(I=1+Math.sign(v)*x),ui(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(nh(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=pt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,k=isFinite(p)?p:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let E="none";if(L?E="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),E="active_low_latency"):b!==0&&k<x?E="live_forward_buffering":k<x+I&&(E="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),E==="live_forward_buffering"||E==="live_with_target_offset"){let $=d-(x+v),y=this.normolizeLiveOffset(Math.trunc(b+$/f)),O=Math.abs(y-b),M=0;!p||O<=this.tuning.dashCmafLive.offsetCalculationError?M=b:y>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(M=y),this.manifestUrlString=ee(this.manifestUrlString,M,2)}(E==="live_with_target_offset"||E==="live_forward_buffering")&&(d=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Bt(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(di(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=Bt(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(di(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),h=ci({allBuffersFull:l,someBufferEnded:c}).pipe(mr(),di(({allBuffersFull:d,someBufferEnded:p})=>d&&p),Os(d=>d));if(this.representationSubscription.add(Bt(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Bt(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Le(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&br(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=en(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){li(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?tn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){li(this.element),this.state$.setState("running"),this.subscription.add(Bt(...oh.map(e=>ot(this.element,e)),ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ot(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&le(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=tn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=o<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",fr(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=en(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){li(this.element),li(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),le(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Pu(this.element)||Pu(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",fr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){br(this.element)&&br(this.source)&&br(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=sh(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-a<=r&&o.to+a>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",fr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Ns=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,a=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:a},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Du=`attribute vec2 a_vertex;
124
124
  attribute vec2 a_texel;
125
125
 
126
126
  varying vec2 v_texel;
@@ -131,7 +131,7 @@ void main(void) {
131
131
  // save texel vector to pass to fragment shader
132
132
  v_texel = a_texel;
133
133
  }
134
- `;var Tl=`#ifdef GL_ES
134
+ `;var Bu=`#ifdef GL_ES
135
135
  precision highp float;
136
136
  precision highp int;
137
137
  #else
@@ -174,13 +174,6 @@ void main(void) {
174
174
  // sample using new coordinates
175
175
  gl_FragColor = texture2D(u_texture, tc);
176
176
  }
177
- `;var Li=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new ya(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ta(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(yl,this.gl.VERTEX_SHADER),i=this.createShader(Tl,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[s,a,o,u,l,p,c,d]}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}};import{isNullable as ih,now as Dr,once as rh,Subscription as sh,ValueSubject as Un,isNonNullable as ah,safeStorage as Hn,filterChanged as nh}from"@vkontakte/videoplayer-shared/evergreen";var Ia="stalls_manager_metrics",jn="stalls_manager_abr_params",Il="stalls_manager_default_tuning_abr_params",zn=class{constructor(){this.isSeeked$=new Un(!1);this.isBuffering$=new Un(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new sh;this.severeStallOccurred$=new Un(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(jn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Dr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Dr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Il)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(jn),this.setStoredData(Il,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ia,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,o)=>a+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ia,[]),this.setStoredData(jn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=a*Math.min(t/(o*u),1),p=this.abrTuningParams;return e<i-r?p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(p={bitrateFactorAtEmptyBuffer:Math.min(p.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(p.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(p.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor,this.abrParams.containerSizeFactor)}),p}getStoredData(e,t="{}"){return JSON.parse(Hn.get(e)??t)}setStoredData(e,t){Hn.set(e,JSON.stringify(t))}removeStoredData(e){Hn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ia,"[]"),r=t/e,s=i.length?Lt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ia,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(rh()).subscribe(t=>this.providerStartWatchingTimestamp=Dr())),this.subscription.add(this.currentStallDuration$.pipe(nh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(ih(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=Dr(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ah(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Dr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},xa=zn;import{combine as oh,map as uh,observeElementSize as lh,Subscription as ch,ValueSubject as Qn,noop as dh}from"@vkontakte/videoplayer-shared/evergreen";var Ea=class{constructor(){this.subscription=new ch;this.pipSize$=new Qn(void 0);this.videoSize$=new Qn(void 0);this.elementSize$=new Qn(void 0);this.pictureInPictureWindowRemoveEventListener=dh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(lh(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(oh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(uh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var si=class{constructor(e){this.subscription=new Sh;this.videoState=new _("stopped");this.observableVideo=null;this.droppedFramesManager=new yi;this.stallsManager=new xa;this.elementSizeManager=new Ea;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return hh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Li(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(Ee(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new va({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;gh(this.observableVideo)&&(this.observableVideo=Ne(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:xl.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,o)=>this.subscription.add(a.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Wn(l=>!!l.length),kl()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(qn(l=>l.to.state!=="none"),ka());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Wn(El),kl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(qn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(mh(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of p.audio){d.push(Pn(h));let m=[];for(let f of h.representations){let b=tl(f);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(d)}let c=[];for(let d of p.video){c.push(Mn(d));let h=[];for(let m of d.representations){let f=el({...m,streamId:d.id});f&&(h.push(f),this.videoTracksMap.set(f,{stream:d,representation:m}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(c);for(let d of p.text)for(let h of d.representations){let m=il(d,h);this.textTracksMap.set(m,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(wa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bh(this.video,"progress")).pipe(Wn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[d,h]=c,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===d.id);El(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ka()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Mn(d))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ka()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Pn(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(qn(({to:l})=>l==="ready"),ka());this.subscription.add(wa(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Gn(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(wa(o,this.player.state$.stateChangeEnded$,Gn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=wa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Gn(["init"])).pipe(fh(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Wi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?Zs:Js,i=this.params.tuning.useNewAutoSelectVideoTrack?mt:Xs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:g})=>g===o),p=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=[...this.videoStreamsMap.keys()].find(({id:g})=>g===c.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let m=Ie(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(m/Math.min(f,b||1/0),1),x=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:g})=>g===x?.id)??this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!a){let g=e(l,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,g?.bitrate??-1/0)}if(p){let g=e(p,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,g?.bitrate??-1/0)}}let E=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:p,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),L=a?E??l:l??E,V=v&&t(L,h,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(L)?.representation,w=V&&this.audioTracksMap.get(V)?.representation;if(k&&w)return[k,w];if(k&&!w&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).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:xl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var Vr=class extends si{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Yn,merge as wl,filter as Al,filterChanged as vh,isNullable as Kn,map as Pl,ValueSubject as Xn,isNonNullable as yh}from"@vkontakte/videoplayer-shared/evergreen";var Cr=class extends si{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let a=new Xn(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Pl(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Yn({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Pl(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Al(o=>yh(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Yn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:wl(i.playbackRateState$,new Xn(1))}).pipe(Al(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||Kn(l)||(e=o-l)})).add(Yn({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:wl(i.playbackRateState$,new Xn(1))}).pipe(vh((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||Kn(o)||Kn(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=rl(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as pm,assertNonNullable as hm,debounce as mm,ErrorCategory as ic,filter as bo,filterChanged as Ca,fromEvent as fm,isNonNullable as rc,isNullable as bm,map as go,merge as Oa,observableFrom as So,once as sc,Subscription as gm}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as co,assertNonNullable as Di,combine as Vi,ErrorCategory as ct,filter as $a,filterChanged as ms,flattenObject as fs,fromEvent as ft,getTraceSubscriptionMethod as im,interval as po,isNonNullable as bs,isNullable as ec,map as Ci,merge as ci,now as ho,Subject as Ra,Subscription as mo,tap as rm,throttle as tc,ValueSubject as le}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Th,ErrorCategory as Ml,Subject as Ll}from"@vkontakte/videoplayer-shared/evergreen";var Ih=18,Bl=!1;try{Bl=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=Ih}catch(n){console.error(n)}var Jn=class{constructor(e){this.bufferFull$=new Ll;this.error$=new Ll;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Ml.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Bl&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ml.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:Th(t)}}},$l=Jn;import{abortable as Qt,assertNonNullable as je,ErrorCategory as ui,fromEvent as no,getExponentialDelay as oo,isNonNullable as $i,isNullable as Ae,now as Ma,once as qh,Subject as Gh,Subscription as Yh,ValueSubject as li}from"@vkontakte/videoplayer-shared/evergreen";var z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=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,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Bi=class extends z{};var Or=class extends z{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,a=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(a);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Fr=class extends z{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var _r=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends z{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Nr=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ur=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hr=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var ai=class extends ie{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qr=class extends ie{constructor(e,t){switch(super(e,t),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 Wr=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var qr=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Gr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yr=class extends ie{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()}};var Kr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jr=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var es=class extends ie{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())}};var ts=class extends ie{constructor(t,i){super(t,i);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 is=class extends ie{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var rs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends ie{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var as=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Eh={ftyp:Fr,moov:_r,mvhd:Nr,moof:Ur,mdat:Hr,sidx:ai,trak:jr,mdia:Gr,mfhd:Jr,tkhd:Yr,traf:Zr,tfhd:es,tfdt:ts,trun:is,minf:Kr,sv3d:zr,st3d:Qr,prhd:Wr,proj:Xr,equi:qr,uuid:Or,stbl:rs,stsd:ss,avc1:as,unknown:Bi},Rt=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!a.size)break;t.push(a),i+=a.size}catch{break}return t}createBox(e,t){let i=Eh[e];return i?new i(t,new n):new Bi(t,new n)}};var zt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var wh=new TextDecoder("ascii"),Ah=n=>wh.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Ph=n=>{let e=new ai(n,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,o})},Mh=(n,e)=>{let i=new Rt().parse(n),r=new zt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let o=s[0],u=a[a.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Lh=n=>{let t=new Rt().parse(n),i=new zt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},Bh=n=>{let t=new Rt().parse(n);return new zt(t).find("sidx")?.timescale},$h=(n,e)=>{let i=new Rt().parse(n),s=new zt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=a.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Rh=n=>{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}}},i=new Rt().parse(n),r=new zt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Rl={validateData:Ah,parseInit:Rh,getIndexRange:()=>{},parseSegments:Ph,parseFeedableSegmentChunk:Mh,getChunkEndTime:$h,getServerLatencyTimestamps:Lh,getTimescaleFromIndex:Bh};import{assertNonNullable as eo,isNonNullable as Ol,isNullable as Vh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Dh}from"@vkontakte/videoplayer-shared/evergreen";var Dl={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"}},Vl=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ns(n,t),r=i in Dl,s=r?Dl[i].type:"binary",a=n.getUint8(t),o=0;a&128?o=1:a&64?o=2:a&32?o=3:a&16?o=4:a&8?o=5:a&4?o=6:a&2?o=7:a&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=a&255>>o,p=ns(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+d):h=new DataView(n.buffer,n.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},ns=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},lt=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ns(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:Dh(e)}},ni=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Vl(i);if(!e(r))return;r.type==="master"&&ni(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Cl=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Vl(n);return ni(r.value,({tag:s,type:a,value:o})=>(s===17143?e=lt(o,a):s===17026?t=lt(o,a):s===17029&&(i=lt(o,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Fl=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ch=[231,22612,22743,167,171,163,160,175],Oh=n=>{let e,t,i,r,s=!1,a=!1,o=!1,u,l,p=!1,c=0;return ni(n,({tag:d,type:h,value:m,valueSize:f})=>{if(d===21419){let b=lt(m,h);l=ns(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=lt(m,h):d===17545?r=lt(m,h):d===21420&&l===475249515?u=lt(m,h):d===374648427?ni(m,({tag:b,type:S,value:x})=>b===30321?(p=lt(x,S)===1,!1):!0):s&&a&&Fl.includes(d)&&(o=!0),!o}),eo(e,"Failed to parse webm Segment start"),eo(t,"Failed to parse webm Segment end"),eo(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Fh=n=>{if(Vh(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_h=(n,e)=>{let t=!1,i=!1,r=o=>Ol(o.time)&&Ol(o.position),s=[],a;return ni(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=lt(l,u));break;case 183:break;case 241:a&&(a.position=lt(l,u));break;default:t&&Fl.includes(o)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((o,u)=>{let{time:l,position:p}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Nh=n=>{let e=0,t=!1;try{ni(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ch.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},_l={validateData:Cl,parseInit:Oh,getIndexRange:Fh,parseSegments:_h,parseFeedableSegmentChunk:Nh};var os=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return _l;case"mp4":return Rl}}throw new ReferenceError(`Unsupported mime type ${n}`)};import{isNonNullable as zh,isNullable as ql}from"@vkontakte/videoplayer-shared/evergreen";var Nl=n=>{try{let e=Uh(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(o=>{let u=a[o];(typeof u>"u"||u==="")&&delete a[o]}),a}return null}catch{return null}};function Uh(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
178
- (?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
179
- (-(?<script>[a-z]{4}))?
180
- (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
181
- (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
182
- (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
183
- (?:-(?<privateuse>(?:${e})))?
184
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}import{videoSizeToQuality as Hh,throttleFn as jh}from"@vkontakte/videoplayer-shared/evergreen";var Ul=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let o=(s?Ft(s):void 0)??Hh({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Hl=({id:n,bitrate:e})=>({id:n,bitrate:e}),jl=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),zl=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),io=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ro=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),so=n=>"url"in n,Ve=n=>n.type==="template",us=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ql=n=>{n.sort((t,i)=>t.from-i.from);let e=[n[0]];for(let t=1;t<n.length;t++){let{from:i,to:r}=n[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(n[t])}return e},oi=(n,e)=>{for(let t of n)if(e(t))return t;return null},Wl=n=>{let e=!1,t=jh(()=>{e=!0},n);return()=>{try{return t(),e}finally{e=!1}}};var Gl=n=>{if(!n?.startsWith("P"))return;let e=(a,o)=>{let u=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Dt=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(o,u)=>ql(s)?o:ql(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Yl=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,x=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((w,g)=>({...w,[g.id]:g.children}),{}),E=v.reduce((w,g)=>({...w,[g.id]:g.getAttribute("duration")}),{});x?S=Gl(x):Object.values(E).filter(w=>w).length&&!u?S=Object.values(E).reduce((w,g)=>w+(Gl(g)??0),0):f&&(S=parseInt(f,10));let L=0,V=s.getAttribute("profiles")?.split(",")??[];for(let w of v.map(g=>g.id))for(let g of I[w]){let R=g.getAttribute("id")??"id"+(L++).toString(10),y=g.getAttribute("mimeType")??"",T=g.getAttribute("codecs")??"",A=g.getAttribute("contentType")??y?.split("/")[0],ee=g.getAttribute("profiles")?.split(",")??[],$=Nl(g.getAttribute("lang")??"")??{},N=g.querySelector("Label")?.textContent?.trim()??void 0,Y=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),he=g.querySelector("Role")?.getAttribute("value")??void 0,se=A,X={id:R,language:$.language,isDefault:he==="main",label:N,codecs:T,hdr:se==="video"&&xi(T),mime:y,representations:[]};for(let M of Y){let D=M.getAttribute("lang")??void 0,Se=N??g.getAttribute("label")??M.getAttribute("label")??void 0,me=M.querySelector("BaseURL")?.textContent?.trim()??"",J=new URL(me||o,e).toString(),fe=M.getAttribute("mimeType")??y,ze=M.getAttribute("codecs")??T??"",Pe;if(A==="text"){let oe=M.getAttribute("id")||"",Qe=$.privateuse?.includes("x-auto")||oe.includes("_auto"),ge=M.querySelector("SegmentTemplate");if(ge){let rt={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},bt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(ge.getAttribute("startNumber")??"",10)??1,We=parseInt(ge.getAttribute("timescale")??"",10),Yt=ge.querySelectorAll("SegmentTimeline S")??[],qe=ge.getAttribute("media");if(!qe)continue;let St=[],vt=0,yt="",Ge=0,st=gt,W=0;for(let ae of Yt){let Me=parseInt(ae.getAttribute("d")??"",10),Z=parseInt(ae.getAttribute("r")??"",10)||0,ve=parseInt(ae.getAttribute("t")??"",10);W=Number.isFinite(ve)?ve:W;let Le=Me/We*1e3,Ye=W/We*1e3;for(let ce=0;ce<Z+1;ce++){let ye=Dt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:(W+ce*Me).toString(10)}),Ke=(Ye??0)+ce*Le,nt=Ke+Le;st++,St.push({time:{from:Ke,to:nt},url:ye})}W+=(Z+1)*Me,vt+=(Z+1)*Le}Ge=W/We*1e3,yt=Dt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:W.toString(10)});let at={time:{from:Ge,to:1/0},url:yt},be={type:"template",baseUrl:J,segmentTemplateUrl:qe,initUrl:"",totalSegmentsDurationMs:vt,segments:St,nextSegmentBeyondManifest:at,timescale:We};Pe={id:oe,kind:"text",segmentReference:be,profiles:[],duration:S,bitrate:bt,mime:"",codecs:"",width:0,height:0,isAuto:Qe}}else Pe={id:oe,isAuto:Qe,kind:"text",url:J}}else{let oe=M.getAttribute("contentType")??fe?.split("/")[0]??A,Qe=g.getAttribute("profiles")?.split(",")??[],ge=parseInt(M.getAttribute("width")??"",10),rt=parseInt(M.getAttribute("height")??"",10),bt=parseInt(M.getAttribute("bandwidth")??"",10)/1e3,gt=M.getAttribute("frameRate")??"",We=M.getAttribute("quality")??void 0,Yt=gt?aa(gt):void 0,qe=M.getAttribute("id")??"id"+(L++).toString(10),St=oe==="video"?`${rt}p`:oe==="audio"?`${bt}Kbps`:ze,vt=`${qe}@${St}`,yt=[...V,...ee,...Qe],Ge,st=M.querySelector("SegmentBase"),W=M.querySelector("SegmentTemplate")??re;if(st){let be=M.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ae,Me]=be.split("-").map(ye=>parseInt(ye,10)),Z={from:ae,to:Me},ve=M.querySelector("SegmentBase")?.getAttribute("indexRange"),[Le,Ye]=ve?ve.split("-").map(ye=>parseInt(ye,10)):[],ce=ve?{from:Le,to:Ye}:void 0;Ge={type:"byteRange",url:J,initRange:Z,indexRange:ce}}else if(W){let be={representationId:M.getAttribute("id")??void 0,bandwidth:M.getAttribute("bandwidth")??void 0},ae=parseInt(W.getAttribute("timescale")??"",10),Me=W.getAttribute("initialization")??"",Z=W.getAttribute("media"),ve=parseInt(W.getAttribute("startNumber")??"",10)??1,Le=Dt(Me,be);if(!Z)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=W.querySelectorAll("SegmentTimeline S")??[],ce=[],ye=0,Ke="",nt=0;if(Ye.length){let Tt=ve,ne=0;for(let Xe of Ye){let de=parseInt(Xe.getAttribute("d")??"",10),Be=parseInt(Xe.getAttribute("r")??"",10)||0,It=parseInt(Xe.getAttribute("t")??"",10);ne=Number.isFinite(It)?It:ne;let Kt=de/ae*1e3,Ja=ne/ae*1e3;for(let xt=0;xt<Be+1;xt++){let Za=Dt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:(ne+xt*de).toString(10)}),Fi=(Ja??0)+xt*Kt,en=Fi+Kt;Tt++,ce.push({time:{from:Fi,to:en},url:Za})}ne+=(Be+1)*de,ye+=(Be+1)*Kt}nt=ne/ae*1e3,Ke=Dt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:ne.toString(10)})}else if(zh(S)){let ne=parseInt(W.getAttribute("duration")??"",10)/ae*1e3,Xe=Math.ceil(S/ne),de=0;for(let Be=1;Be<Xe;Be++){let It=Dt(Z,{...be,segmentNumber:Be.toString(10),segmentTime:de.toString(10)});ce.push({time:{from:de,to:de+ne},url:It}),de+=ne}nt=de,Ke=Dt(Z,{...be,segmentNumber:Xe.toString(10),segmentTime:de.toString(10)})}let Xa={time:{from:nt,to:1/0},url:Ke};Ge={type:"template",baseUrl:J,segmentTemplateUrl:Z,initUrl:Le,totalSegmentsDurationMs:ye,segments:ce,nextSegmentBeyondManifest:Xa,timescale:ae}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!fe)continue;let at={video:"video",audio:"audio",text:"text"}[oe];if(!at)continue;se||=at,Pe={id:vt,kind:at,segmentReference:Ge,profiles:yt,duration:S,bitrate:bt,mime:fe,codecs:ze,width:ge,height:rt,fps:Yt,quality:We}}X.language||=D,X.label||=Se,X.mime||=fe,X.codecs||=ze,X.hdr||=se==="video"&&xi(ze),X.representations.push(Pe)}if(se){let M=r[se].find(D=>D.id===X.id);if(M&&X.representations.every(D=>Ve(D.segmentReference)))for(let D of M.representations){let me=X.representations.find(fe=>fe.id===D.id)?.segmentReference,J=D.segmentReference;J.segments.push(...me.segments),J.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[se].push(X)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{fromEvent as Qh,Subscription as Wh}from"@vkontakte/videoplayer-shared/evergreen";var Aa=n=>{let e=[];for(let t=0;t<n.length;t++){let i=Math.floor(n.start(t)*1e3),r=Math.ceil(n.end(t)*1e3);e.push(i,r)}return e};var Pa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Wh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Qh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!C(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Aa(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],o=t[i+1];if(a>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var ls=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new li(0);this.currentLowLatencySegmentLength$=new li(0);this.currentSegmentLength$=new li(0);this.onLastSegment$=new li(!1);this.fullyBuffered$=new li(!1);this.playingRepresentation$=new li(void 0);this.playingRepresentationInit$=new li(void 0);this.error$=new Gh;this.gaps=[];this.subscription=new Yh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Qt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $l(this.sourceBuffer),this.sourceBufferBufferedDiff=new Pa(this.mediaSource,this.sourceBuffer),this.subscription.add(no(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(no(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ui.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ie(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,a*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),je(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();$i(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),je(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();$i(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Qt(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!Ve(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r);let s=this.segments.get(i);je(s,"No segments for starting representation");let a=this.initData.get(i);if(je(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Qt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);je(s,`No such representation ${i}`);let a=this.segments.get(i),o=this.initData.get(i);if(Ae(o)||Ae(a)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),a=this.segments.get(i),je(a,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();$i(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ae(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||$i(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);$i(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ie(this.sourceBuffer.buffered,e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&Ti(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Ie(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))p="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&Ie(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Ie(this.sourceBuffer.buffered,e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;$i(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Ve(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],o=a.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ve(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Dt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,S=h>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+x||r<x&&m-h>=x||m<=i+x;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(ke(this.sourceBuffer.buffered,h)&&ke(this.sourceBuffer.buffered,m)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(o<=p||u<=c);d++){let h=a[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){Ve(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Qt(o,async function*(){let p=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(a,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Ma(),!p)return;let c=new DataView(p),d=os(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),us(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ve(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Qt(a,async function*(){let u=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),no(window,"online").pipe(qh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:a,priority:i}),this.lastDataObtainedTimestampMs=Ma(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),us(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ve(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ma(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ve(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ma();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=os(a.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===d?f:os(o.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(Ae(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ke(this.sourceBuffer.buffered,e.segment.time.from,100)&&ke(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ui.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",so(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?Qt(this.destroyAbortController.signal,async function*(){let o=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,os(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&Ve(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ui.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ae(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=o=>{if(s>=t)return;r.push({...o.time});let u=so(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&a(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)["none","partially_ejected"].includes(d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};a(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&a(l)}return r.length?(r=Ql(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ae(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let a=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(a>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ui.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ae(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Ae(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Aa(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=a&&d+t>=o),(a>=c&&a<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ui.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as cs,assertNever as Kl,fromEvent as Xl,merge as Kh,now as ds,Subject as Jl,ValueSubject as uo,flattenObject as Ri,ErrorCategory as ps,SubscriptionRemovable as Xh}from"@vkontakte/videoplayer-shared/evergreen";var Ba=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new uo(void 0);this.lastConnectionReused$=new uo(void 0);this.lastRequestFirstBytes$=new uo(void 0);this.recoverableError$=new Jl;this.error$=new Jl;this.abortAllController=new AbortController;this.subscription=new Xh;this.fetchManifest=cs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ht(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ua(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(La);return r?(t.log("success",Ri({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Ri({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=cs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let y=new URL(l,location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),l=y.toString();break}default:Kl(t)}this.requestQuic&&(l=Ht(l));let d=this.abortAllController.signal,h;if(a){let y=new AbortController;if(h=Kh(Xl(this.abortAllController.signal,"abort"),Xl(a,"abort")).subscribe(()=>{try{y.abort()}catch(T){La(T)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(T){La(T)}d=y.signal}let m=ds();c.log("startRequest",Ri({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:p,signal:d}),b=ds();if(!f)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){this.unsubscribeAbortSubscription(h);let y=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:y}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let y=ds(),T={requestStartedAt:m,requestEndedAt:y,duration:y-m};return c.log("endRequest",Ri(T)),c.end(),f.arrayBuffer()}let S=f.body;if(o){let y;[S,y]=f.body.tee(),this.throughputEstimator?.trackStream(y,u)}let x=S.getReader(),v,I=parseInt(f.headers.get("content-length")??"",10);Number.isFinite(I)&&(v=I),!v&&i&&(v=i.to-i.from+1);let E=0,L=v?new Uint8Array(v):new Uint8Array(0),V=!1,k=y=>{this.unsubscribeAbortSubscription(h),V=!0,La(y)},w=cs(d,async function*({done:y,value:T}){if(E===0&&this.lastRequestFirstBytes$.next(ds()-m),d.aborted){this.unsubscribeAbortSubscription(h);return}if(!y&&T){if(v)L.set(T,E),E+=T.byteLength;else{let A=new Uint8Array(L.length+T.length);A.set(L),A.set(T,L.length),L=A,E+=T.byteLength}r?.(new DataView(L.buffer),E),yield x?.read().then(w,k)}}.bind(this));yield x?.read().then(w,k),this.unsubscribeAbortSubscription(h);let g=ds(),R={failed:V,requestStartedAt:m,requestEndedAt:g,duration:g-m};return V?(c.error("endRequest",Ri(R)),c.end(),null):(c.log("endRequest",Ri(R)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=cs(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,o=s,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),o=Math.max(p,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-a,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=cs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Kl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ps.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ps.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ps.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ps.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ps.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},La=n=>{if(!us(n))throw n};import{isNullable as Jh,ValueSubject as Zh}from"@vkontakte/videoplayer-shared/evergreen";var hs=class n{constructor(e,t){this.currentRepresentation$=new Zh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Jh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<a||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ve(t.segmentReference))}};var sm=["progress","play","seeked","stalled","waiting"],am=["timeupdate","progress","loadeddata","playing","seeked"];var Da=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new mo;this.representationSubscription=new mo;this.state$=new _("none");this.currentVideoRepresentation$=new le(void 0);this.currentVideoRepresentationInit$=new le(void 0);this.currentAudioRepresentation$=new le(void 0);this.currentVideoSegmentLength$=new le(0);this.currentAudioSegmentLength$=new le(0);this.error$=new Ra;this.lastConnectionType$=new le(void 0);this.lastConnectionReused$=new le(void 0);this.lastRequestFirstBytes$=new le(void 0);this.currentLiveTextRepresentation$=new le(null);this.isLive$=new le(!1);this.isActiveLive$=new le(!1);this.isLowLatency$=new le(!1);this.liveDuration$=new le(0);this.liveSeekableDuration$=new le(0);this.liveAvailabilityStartTime$=new le(0);this.liveStreamStatus$=new le(void 0);this.bufferLength$=new le(0);this.liveLatency$=new le(void 0);this.liveLoadBufferLength$=new le(0);this.livePositionFromPlayer$=new le(0);this.currentStallDuration$=new le(0);this.videoLastDataObtainedTimestamp$=new le(0);this.fetcherRecoverableError$=new Ra;this.fetcherError$=new Ra;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ra;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=co(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Yl(e??"",this.manifestUrlString)}catch(a){let o=sa(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(o)}if(!t)return null;let i=(a,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let u=t.streams[a].filter(({mime:c,codecs:d})=>i(a,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=ba(l);if(p&&(r[a]=u.filter(({codecs:c})=>c.startsWith(p))),a==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);O.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",fs(s)),s}.bind(this));this.initRepresentations=co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",fs({initialVideo:e,initialAudio:t,sourceHls:i})),Di(this.manifest),Di(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new mo,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(ft(d,"error").pipe($a(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new ls("video",this.source,o,a),this.bufferManagers=[this.videoBufferManager],bs(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ls("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}hs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new hs(this.manifest.streams.text,a)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ci(...am.map(d=>ft(this.element,d))).pipe(Ci(d=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),ms(),rm(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ci(ft(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ms()).subscribe(h=>this.liveStreamEndTimestamp=ho())),this.subscription.add(ft(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=po(1e3).subscribe(h=>{let m=Ct(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ft(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Vi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ci(({isActiveLive:h,isLowLatency:m})=>h&&m),ms()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||wi(this.element,1)})),this.representationSubscription.add(Vi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe($a(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Vi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe($a(({isLive:h})=>h),ms((h,m)=>m.bufferLength<h.bufferLength),Ci(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=Ct(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Vi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>S&&(I=1+Math.sign(v)*x),wi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(Vi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(tc(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=Ct(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(V);let k="none";if(L?k="active_low_latency":this.isLowLatency$.getValue()&&V?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),k==="live_forward_buffering"||k==="live_with_target_offset"){let w=d-(x+v),g=this.normolizeLiveOffset(Math.trunc(b+w/f)),R=Math.abs(g-b),y=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?y=b:g>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(y=g),this.manifestUrlString=pe(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ci(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Ci(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ci(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Ci(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Vi({allBuffersFull:l,someBufferEnded:p}).pipe(ms(),Ci(({allBuffersFull:d,someBufferEnded:h})=>d&&h),$a(d=>d));if(this.representationSubscription.add(ci(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ci(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Ve(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&bs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=po(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ba({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Di(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ho()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=pe(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Di(this.element),this.state$.setState("running");let e=ft(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(tc(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(ci(...sm.map(t=>ft(this.element,t)),ft(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ft(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ft(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ke(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ho(),a=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",fs(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=po(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Di(this.element),Di(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ke(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ec(this.element)||ec(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",fs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){bs(this.element)&&bs(this.source)&&bs(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=im(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let u=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",fs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as nm,map as om,observeElementSize as um,Subscription as lm,ValueSubject as fo,noop as cm}from"@vkontakte/videoplayer-shared/evergreen";var Va=class{constructor(){this.subscription=new lm;this.pipSize$=new fo(void 0);this.videoSize$=new fo(void 0);this.elementSize$=new fo(void 0);this.pictureInPictureWindowRemoveEventListener=cm}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(um(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(nm({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(om(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var di=class{constructor(e){this.subscription=new gm;this.videoState=new _("stopped");this.observableVideo=null;this.droppedFramesManager=new yi;this.stallsManager=new xa;this.elementSizeManager=new Va;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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()):i?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return pm(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Li(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(Ee(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Da({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;bm(this.observableVideo)&&(this.observableVideo=Ne(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:ic.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,o)=>this.subscription.add(a.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bo(c=>!!c.length),sc()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(go(c=>c.to.state!=="none"),Ca());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(bo(rc),sc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(go(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(hm(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of d.audio){m.push(io(f));let b=[];for(let S of f.representations){let x=Hl(S);b.push(x),this.audioTracksMap.set(x,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(ro(m));let f=[];for(let b of m.representations){let S=Ul({...b,streamId:m.id});S&&(f.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(h);for(let m of d.text)for(let f of m.representations){let b=jl(m,f);this.textTracksMap.set(b,{stream:m,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Wl(o)||null;this.subscription.add(Oa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,fm(this.video,"progress")).pipe(bo(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let f=oi(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);rc(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ca()).subscribe(c=>{let d=oi(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ro(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ca()).subscribe(c=>{let d=oi(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(io(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(go(({to:c})=>c==="ready"),Ca());this.subscription.add(Oa(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,So(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Oa(l,this.player.state$.stateChangeEnded$,So(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=Oa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,So(["init"])).pipe(mm(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Wi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?Zs:Js,i=this.params.tuning.useNewAutoSelectVideoTrack?mt:Xs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=oi(this.videoTracksMap.keys(),k=>k.id===o),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=oi(this.videoStreamsMap.keys(),k=>k.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Ie(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,f||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=S?.id&&oi(this.audioStreamsMap.keys(),k=>k.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(x){if(u&&!a){let k=e(u,d,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,k?.bitrate??-1/0)}if(l){let k=e(l,d,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,k?.bitrate??-1/0)}}let I=u;(a||!I)&&(I=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=x&&t(I,d,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=this.videoTracksMap.get(I)?.representation,V=E&&this.audioTracksMap.get(E)?.representation;L&&V?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=V):L&&!V&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).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:ic.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var gs=class extends di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vo,merge as ac,filter as nc,filterChanged as Sm,isNullable as yo,map as oc,ValueSubject as To,isNonNullable as vm}from"@vkontakte/videoplayer-shared/evergreen";var Ss=class extends di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let a=new To(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(oc(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vo({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(oc(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(nc(o=>vm(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(vo({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ac(i.playbackRateState$,new To(1))}).pipe(nc(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||yo(l)||(e=o-l)})).add(vo({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ac(i.playbackRateState$,new To(1))}).pipe(Sm((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||yo(o)||yo(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=zl(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var uc="X-Playback-Duration",Io=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(uc)?parseInt(e.headers.get(uc),10):void 0};import{assertNever as Lm,combine as Bm,debounce as $m,ErrorCategory as Na,filter as Rm,filterChanged as Dm,isNonNullable as dc,isNullable as Ua,map as pc,merge as Vm,observableFrom as Cm,Subscription as Om,ValueSubject as Eo,VideoQuality as Fm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as ym,getExponentialDelay as Tm}from"@vkontakte/videoplayer-shared/evergreen";var Im=n=>{let e=null;if(n.QUALITY&&(e=Ft(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ym({width:t,height:i})}return e??null},xm=(n,e)=>{let t=n.split(`
185
- `),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],o=a.match(/^#EXT-X-STREAM-INF:(.+)/),u=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=Object.fromEntries(o[1].split(",").map(b=>b.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=Im(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,S]=l.RESOLUTION.split("x").map(x=>parseInt(x,10));b&&S&&(m={width:b,height:S})}let f=new URL(t[++s],e).toString();c&&i.push({id:p,quality:c,url:f,bandwidth:d,size:m,fps:h})}if(u){let l=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Em=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),xo=0,lc=async(n,e=n,t,i)=>{let s=await(await fetch(n,i)).text();xo+=1;try{let{qualityManifests:a,textTracks:o}=xm(s,e);return{qualityManifests:a,textTracks:o}}catch{if(xo<=t.manifestRetryMaxCount)return await Em(Tm(xo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),lc(n,e,t)}return{qualityManifests:[],textTracks:[]}},Fa=lc;import{isNonNullable as km,Subscription as wm,throttle as Am,ValueSubject as cc,Subject as Pm,ErrorCategory as Mm}from"@vkontakte/videoplayer-shared/evergreen";var _a=class{constructor(e,t,i,r,s){this.subscription=new wm;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new cc(null);this.getCurrentTime$=new cc(null);this.error$=new Pm;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Am(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(a,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
186
- `),s=0;for(let a=0;a<r.length;++a){let o=r[a];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++a],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(km(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Mm.WTF,thrown:t,message:e})}};var vs=class{constructor(e){this.subscription=new Om;this.videoState=new _("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Eo([]);this.liveOffset=new Zt;this.manifestStartTime$=new Eo(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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 l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Lm(t)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Fm.INVARIANT,url:this.params.source.url};let t=(i,r)=>Fa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new _a(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new tt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Na.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Na.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(Ee(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Eo(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Na.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),s(it(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(Dm(),pc(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dc(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Ee(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Bm({startTime:this.manifestStartTime$.pipe(Rm(dc)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(pc(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Vm(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Cm(["init"])).pipe($m(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.selectManifest();if(Ua(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=pe(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Io(a).then(o=>{if(!Ua(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Ua(u)||!isFinite(u))&&fetch(a).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,a).toString();Io(c).then(d=>{Ua(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).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:Na.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=pe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as _m,debounce as Nm,ErrorCategory as ko,fromEvent as wo,isNonNullable as Um,isNullable as Hm,map as hc,merge as mc,observableFrom as fc,Subscription as jm,ValueSubject as zm,VideoQuality as Qm}from"@vkontakte/videoplayer-shared/evergreen";var ys=class{constructor(e){this.subscription=new jm;this.videoState=new _("stopped");this.manifests$=new zm([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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 l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return _m(t)}};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Qm.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(Ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fa(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ko.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ko.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(hc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Um(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Ee(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(hc(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!O.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(mc(wo(o,"addtrack"),wo(o,"removetrack"),wo(o,"change"),fc(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let a=mc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fc(["init"])).pipe(Nm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.selectManifest();if(Hm(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).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:ko.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Wm,assertNonNullable as bc,debounce as qm,ErrorCategory as gc,isHigherOrEqual as Gm,isLowerOrEqual as Ym,isNonNullable as Km,merge as Xm,observableFrom as Jm,Subscription as Zm,map as ef}from"@vkontakte/videoplayer-shared/evergreen";var Ts=class{constructor(e){this.subscription=new Zm;this.videoState=new _("stopped");this.trackUrls={};this.textTracksManager=new tt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.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.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return Wm(e)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:gc.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ef(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),s(it(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Km(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Xm(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Jm(["init"])).pipe(qm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;bc(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];bc(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ht(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ee(t))}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).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:gc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=mt(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||fi(e,a[0].quality,a.at(-1)?.quality)){i();return}let o=e.max?Ym(r,e.max):!0,u=e.min?Gm(r,e.min):!0;o&&u||i(e)}};import{assertNever as vc,debounce as af,merge as yc,observableFrom as nf,Subscription as of,map as Tc,ValueSubject as uf,ErrorCategory as Po,VideoQuality as lf}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as tf}from"@vkontakte/videoplayer-shared/evergreen";var Sc=["stun:videostun.mycdn.me:80"],rf=1e3,sf=3,Ao=()=>null,Ha=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=Ao;this.externalStopCallback=Ao;this.externalErrorCallback=Ao;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{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:Sc}]};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:tf.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){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),rf)}normalizeOptions(e={}){let t={stunServerList:Sc,maxRetryNumber:sf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Is=class{constructor(e){this.videoState=new _("stopped");this.maxSeekBackTime$=new uf(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return vc(e)}};this.subscription=new of,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Oe(e.container,e.tuning),this.liveStreamClient=new Ha(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Po.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(yc(this.videoState.stateChangeStarted$.pipe(Tc(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tc(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(a)}`})}));let r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(a,o)=>this.subscription.add(a.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(it(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(_e(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 vc(a.to)}},i)).add(yc(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,nf(["init"])).pipe(af(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ee(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:lf.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:Po.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).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:Po.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xs=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Es,assertNonNullable as Wt,ErrorCategory as ja,filter as Ac,isNonNullable as Pc,isNullable as bf,map as gf,merge as Sf,once as vf,Subject as xe,Subscription as Mc,ValueSubject as U,flattenObject as Mo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as cf,map as Ic,Subscription as df,Subject as pf}from"@vkontakte/videoplayer-shared/evergreen";var xc=n=>new cf(e=>{let t=new df,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Ic(({from:l,to:p})=>`${l}-${p}`)),r=n.desiredPlaybackState$.stateChangeEnded$,s=n.providerChanged$.pipe(Ic(({type:l})=>l!==void 0)),a=new pf,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>a.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>a.next(u),n.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as hf,Subscription as mf,combine as ff,filter as kc,once as wc}from"@vkontakte/videoplayer-shared/evergreen";function Ec(){return new(window.AudioContext||window.webkitAudioContext)}var Oi=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new mf;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(kc(s=>!!s.type),wc()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){O.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ff({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(kc(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),wc()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ec();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:hf.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var yf={chunkDuration:5e3,maxParallelRequests:5},ks=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new xe;this.noAvailableProvidersError$=new xe;this.volumeMultiplierError$=new xe;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new xe,fetcherError$:new xe,fetcherRecoverableError$:new xe,warning$:new xe,willSeekEvent$:new xe,soundProhibitedEvent$:new xe,seekedEvent$:new xe,loopedEvent$:new xe,endedEvent$:new xe,firstBytesEvent$:new xe,loadedMetadataEvent$:new xe,firstFrameEvent$:new xe,canplay$:new xe,isLive$:new U(void 0),isLiveEnded$:new U(null),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new xe,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new Mc;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=hl([...fl(this.params.tuning),...ml(this.params.tuning)],this.params.tuning).filter(l=>Pc(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Mo(s)),this.screenFormatsIterator=new xs(s);let a=[...Cn(!0),...Cn(!1)];this.chromecastFormatsIterator=new xs(a.filter(l=>Pc(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Oi.isSupported()&&(this.volumeMultiplierManager=new Oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}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(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(bf(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ja.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination: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"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Es(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,o={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(u),this.params.tuning.useNewDashProvider?new gs({...o,source:u,sourceHls:l}):new Vr({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wt(u),this.params.tuning.useNewDashProvider?new Ss({...o,source:u}):new Cr({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Wt(u),new ys({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wt(u),new vs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Ts({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Uu({...o,source:u,config:{...yf,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Is({container:i,source:u,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Es(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new _i({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:a,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 Es(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Es(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 Es(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);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:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Mc,t=!1,i=0;return e.add(Sf(this.providerOutput.error$.pipe(Ac(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),xc({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gf(r=>({id:`ProviderHangup:${r}`,category:ja.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Ac(({to:s})=>s==="playing"),vf()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===ja.NETWORK,u=r.category===ja.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!p);a={...a,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Mo(a)):this.tracer.error("providerError",Mo(a))})),e}};import{fromEvent as za,once as Tf,combine as If,Subscription as Lc,ValueSubject as Lo,map as xf,filter as Ef,isNonNullable as Qa,now as Ze,safeStorage as Bo}from"@vkontakte/videoplayer-shared/evergreen";var kf=5e3,Bc="one_video_throughput",$c="one_video_rtt",ws=window.navigator.connection,Rc=()=>{let n=ws?.downlink;if(Qa(n)&&n!==10)return n*1e3},Dc=()=>{let n=ws?.rtt;if(Qa(n)&&n!==3e3)return n},Vc=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},$o=class n{constructor(e){this.subscription=new Lc;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Bc)||(e.useBrowserEstimation?Rc():void 0)||kf,i=n.load($c)??(e.useBrowserEstimation?Dc():void 0)??0;if(this.throughput$=new Lo(t),this.rtt$=new Lo(i),this.rttAdjustedThroughput$=new Lo(Vc(t,i,e.rttPenaltyRequestSize)),this.throughput=Bt.getSmoothedValue(t,-1,e),this.rtt=Bt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Rc();a&&this.throughput.next(a);let o=Dc();Qa(o)&&this.rtt.next(o)};ws&&"onchange"in ws&&this.subscription.add(za(ws,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Bo.set(Bc,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Bo.set($c,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(If({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(xf(({throughput:r,rtt:s})=>Vc(r,s,e.rttPenaltyRequestSize)),Ef(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ze(),r=new Lc;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(za(e,"progress").pipe(Tf()).subscribe(s=>{t=s.loaded,i=Ze()}));break;case 1:case 0:r.add(za(e,"loadstart").subscribe(()=>{t=0,i=Ze()}));break}r.add(za(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,o=Ze(),u=a-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ze(),a=0,o=Ze(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,Ze()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=Ze();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(a,m,1,t),a=c.byteLength,s=Ze()}else a+=c.byteLength;o=Ze()}else r+=c.byteLength,a+=c.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Ze()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Ze()-o,this.concurrentDownloads.size),a=0,o=Ze());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Bo.get(e);if(Qa(t))return parseInt(t,10)??void 0}},Cc=$o;import{fillWithDefault as wf,VideoQuality as Wa}from"@vkontakte/videoplayer-shared/evergreen";var Oc={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:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Wa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wa.Q_720P,trafficSavingLimit:Wa.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wa.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1},Fc=n=>({...wf(n,Oc),configName:[...n.configName??[],...Oc.configName]});import{assertNonNullable as qa,combine as Vt,ErrorCategory as Ga,filter as F,filterChanged as q,fromEvent as Do,isNonNullable as Hc,isNullable as Rf,Logger as Df,map as Q,mapTo as jc,merge as qt,now as Ya,once as H,Subject as G,Subscription as zc,tap as Vo,ValueSubject as B,isHigher as Vf,isInvariantQuality as Qc,flattenObject as Gt,throttle as Co,getTraceSubscriptionMethod as Wc,TracerFactory as Cf,InternalsExposure as Of}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Af,map as Pf,filter as _c,isNonNullable as Mf}from"@vkontakte/videoplayer-shared/evergreen";var Ro=({seekState:n,position$:e})=>Af(n.stateChangeEnded$.pipe(Pf(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),_c(Mf)),e.pipe(_c(()=>n.getState().state==="none")));import{assertNonNullable as Lf}from"@vkontakte/videoplayer-shared/evergreen";var Nc=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Lf(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Bf,once as $f}from"@vkontakte/videoplayer-shared/evergreen";var Uc=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Bf(r=>r.length>0),$f()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Ka=class{constructor(e={configName:[]},t=Cf.createRootTracer(!1)){this.subscription=new zc;this.logger=new Df;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new B(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new B(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new _("stopped"),seekState:new _({state:"none"}),volume:new _({volume:1,muted:!1}),videoTrack:new _(void 0),videoStream:new _(void 0),audioStream:new _(void 0),autoVideoTrackSwitching:new _(!0),autoVideoTrackLimits:new _({}),isLooped:new _(!1),isLowLatency:new _(!1),playbackRate:new _(1),externalTextTracks:new _([]),internalTextTracks:new _([]),currentTextTrack:new _(void 0),textTrackCuesSettings:new _({}),cameraOrientation:new _({x:0,y:0})};this.info={playbackState$:new B(void 0),position$:new B(0),duration$:new B(1/0),muted$:new B(!1),volume$:new B(1),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableQualities$:new B([]),availableQualitiesFps$:new B({}),currentQuality$:new B(void 0),isAutoQualityEnabled$:new B(!0),autoQualityLimitingAvailable$:new B(!1),autoQualityLimits$:new B({}),predefinedQualityLimitType$:new B("unknown"),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),isAudioAvailable$:new B(!0),currentPlaybackRate$:new B(1),currentBuffer$:new B({start:0,end:0}),isBuffering$:new B(!0),isStalled$:new B(!1),isEnded$:new B(!1),isLooped$:new B(!1),isLive$:new B(void 0),isLiveEnded$:new B(null),canChangePlaybackSpeed$:new B(void 0),atLiveEdge$:new B(void 0),atLiveDurationEdge$:new B(void 0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),currentFormat$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),throughputEstimation$:new B(void 0),rttEstimation$:new B(void 0),videoBitrate$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),surface$:new B("none"),chromecastState$:new B("NOT_AVAILABLE"),chromecastDeviceName$:new B(void 0),intrinsicVideoSize$:new B(void 0),availableSources$:new B(void 0),is3DVideo$:new B(!1),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willReady$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new B(void 0),tuningConfigName$:new B([]),enableDebugTelemetry$:new B(!1),dumpTelemetry:Su,getCurrentTime$:new B(null)};if(this.initLogs(),this.tuning=Fc(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cc(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Of("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let a=Reflect.get(i,r,s);return typeof a!="function"?a:(...o)=>{try{return a.apply(i,o)}catch(u){let l=o.map(d=>JSON.stringify(d,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),p=`Player.${String(r)}`,c=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Ga.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",Gt(a)),this.domContainer=Nc(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ks({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?O.isInited$.pipe(F(s=>!!s),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Do(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{qa(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(F(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{qa(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{Uc(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(F(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Rf(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Hc(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(gn(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(F(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=Ya(),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"ready":this.events.willReady$.next();break;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 a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Gt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:Ga.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(a=>a.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:a,currentVideoStream:o})=>a.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Qc(u)?1:Qc(l)?-1:Vf(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let o={};for(let u of a)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(F(a=>Hc(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((a,o)=>Math.round(a)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((a,o)=>Math.round(a)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).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(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(Q(a=>a?{start:a.from,end:a.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.isLiveEnded$.pipe(Vo(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).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(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Vt({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(a=>a.to),q(),Q(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Vt({atLiveEdge:Vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ro({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return a&&Math.abs(o)<l/1e3}),q(),Vo(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:o})=>a&&!o)).subscribe(this.info.atLiveEdge$)).add(Vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:a,position:o,duration:u})=>a&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),Vo(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(a=>a.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(a=>a.volume),q()).subscribe(this.info.volume$)).add(Ro({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(qt(e.providerOutput.endedEvent$.pipe(jc(!0)),e.providerOutput.seekedEvent$.pipe(jc(!1))).pipe(q()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Q(a=>({id:a?`No${a}`:"NoProviders",category:Ga.VIDEO_PIPELINE,message:a?`${a} 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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),Q(a=>a??Ya()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),Q(()=>Ya()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),Q(()=>Ya()-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 B(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new B(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(F(({to:a})=>a==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=qt(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let a=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return a&&!o}),q());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(qt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(qt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":u?l?a?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new zc;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(F(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=mt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput: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(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;qa(this.providerContainer),qa(e),gu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>bu(t)),this.providerContainer.current$.subscribe(({type:t})=>zi("provider",t)),e.duration$.subscribe(t=>zi("duration",t)),e.availableVideoTracks$.pipe(F(t=>!!t.length),H()).subscribe(t=>zi("tracks",t)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(t=>this.subscription.add(t)),zi("codecs",O.video.supportedCodecs)}initTracerSubscription(){let e=Wc(this.tracer.log.bind(this.tracer)),t=Wc(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(F(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(F(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(F(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Vt({currentBuffer:this.info.currentBuffer$.pipe(F(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(Co(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(F(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Co(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),F(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),F(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),F(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(F(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Co(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),F(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ga.DOM,message:String(r)})})};this.subscription.add(qt(Do(document,"visibilitychange"),Do(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gt({quality:t,availableTracks:Gt(e),track:Gt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()}};import{Subscription as FV,Observable as _V,Subject as NV,ValueSubject as UV,VideoQuality as HV}from"@vkontakte/videoplayer-shared/evergreen";var jV=`@vkontakte/videoplayer-core@${Oo}`;export{As as ChromecastState,tn as HttpConnectionType,_V as Observable,Ce as PlaybackState,Ka as Player,Ps as PredefinedQualityLimits,jV as SDK_VERSION,NV as Subject,FV as Subscription,rn as Surface,Oo as VERSION,UV as ValueSubject,Et as VideoFormat,HV as VideoQuality,O as clientChecker,ji as isMobile};
177
+ `;var hi=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ns(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Du,this.gl.VERTEX_SHADER),i=this.createShader(Bu,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,u=e+i,o=t-r,l=e+i,c=t+r,h=e-i,d=t+r;return[s,a,u,o,l,c,h,d]}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}};import{isNullable as dh,now as gr,once as hh,Subscription as ph,ValueSubject as rn,isNonNullable as mh,safeStorage as sn,filterChanged as fh}from"@vkontakte/videoplayer-shared/evergreen";var Hs="stalls_manager_metrics",an="stalls_manager_abr_params",Vu="stalls_manager_default_tuning_abr_params",nn=class{constructor(){this.isSeeked$=new rn(!1);this.isBuffering$=new rn(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ph;this.severeStallOccurred$=new rn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(an):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=gr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(gr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Vu)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(an),this.setStoredData(Vu,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Hs,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,u)=>a+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Hs,[]),this.setStoredData(an,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,l=a*Math.min(t/(u*o),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(sn.get(e)??t)}setStoredData(e,t){sn.set(e,JSON.stringify(t))}removeStoredData(e){sn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Hs,"[]"),r=t/e,s=i.length?at(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Hs,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(hh()).subscribe(t=>this.providerStartWatchingTimestamp=gr())),this.subscription.add(this.currentStallDuration$.pipe(fh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(dh(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=gr(),h=r&&this.currentStallsCount>=r,d=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&c-l>=i+u&&t>=i;(h||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,mh(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&gr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Qs=nn;import{combine as bh,map as gh,observeElementSize as Sh,Subscription as vh,ValueSubject as on,noop as yh}from"@vkontakte/videoplayer-shared/evergreen";var js=class{constructor(){this.subscription=new vh;this.pipSize$=new on(void 0);this.videoSize$=new on(void 0);this.elementSize$=new on(void 0);this.pictureInPictureWindowRemoveEventListener=yh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Sh(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(bh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(gh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Vt=class{constructor(e){this.subscription=new Ah;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new ti;this.stallsManager=new Qs;this.elementSizeManager=new js;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return Ih(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new hi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ve(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new _s({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;wh(this.observableVideo)&&(this.observableVideo=Ie(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Cu.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(un(l=>!!l.length),Fu()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(ln(l=>l.to.state!=="none"),zs());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(un(Ou),Fu()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ln(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Eh(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let p of c.audio){d.push(ja(p));let m=[];for(let f of p.representations){let b=gu(f);m.push(b),this.audioTracksMap.set(b,{stream:p,representation:f})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(d)}let h=[];for(let d of c.video){h.push(za(d));let p=[];for(let m of d.representations){let f=bu({...m,streamId:d.id});f&&(p.push(f),this.videoTracksMap.set(f,{stream:d,representation:m}))}this.videoStreamsMap.set(d,p)}this.params.output.availableVideoStreams$.next(h);for(let d of c.text)for(let p of d.representations){let m=Su(d,p);this.textTracksMap.set(m,{stream:d,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Ws(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,kh(this.video,"progress")).pipe(un(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[d,p]=h,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===d.id);Ou(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(d.id,p?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(zs()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:d}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===d.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(za(d));let m=this.player.calculateDurationFromSegments();m&&this.params.output.duration$.next(m/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(zs()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[h,{stream:d}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===d.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(ja(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(ln(({to:l})=>l==="ready"),zs());this.subscription.add(Ws(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,cn(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Ws(u,this.player.state$.stateChangeEnded$,cn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=Ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cn(["init"])).pipe(xh(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pi:$i,t=this.params.tuning.useNewAutoSelectVideoTrack?Ss:gs,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:bs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:y})=>y===u),c=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:y})=>y===h.id),p=d&&this.videoStreamsMap.get(d);if(!p)return;let m=se(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(m/Math.min(f,b||1/0),1),x=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:y})=>y===x?.id)??this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!a){let y=e(l,p,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,y?.bitrate??-1/0)}if(c){let y=e(c,p,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,y?.bitrate??-1/0)}}let k=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:g,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),L=a?k??l:l??k,P=v&&t(L,p,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=this.videoTracksMap.get(L)?.representation,$=P&&this.audioTracksMap.get(P)?.representation;if(E&&$)return[E,$];if(E&&!$&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ye(this.video),this.tracer.end()}};var Sr=class extends Vt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as dn,merge as _u,filter as Nu,filterChanged as Uu,isNullable as hn,map as Hu,ValueSubject as pn,isNonNullable as Lh}from"@vkontakte/videoplayer-shared/evergreen";var vr=class extends Vt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new pn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Uu()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),h=!c.volume||c.muted;!o&&!l&&h?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Hu(o=>o.to)).subscribe(this.player.isLowLatency$)).add(dn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Hu(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(Nu(o=>Lh(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(dn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:_u(r.playbackRateState$,new pn(1))}).pipe(Nu(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),h=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;h||l<1-d||this.video.paused||hn(c)||(t=o-c)})).add(dn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:_u(r.playbackRateState$,new pn(1))}).pipe(Uu((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let h=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!h&&!this.video.paused&&c>=1-d||hn(o)||hn(l))return;let p=-1*(l-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=vu(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as ep,assertNonNullable as tp,debounce as ip,ErrorCategory as al,filter as An,filterChanged as ia,fromEvent as rp,isNonNullable as nl,isNullable as sp,map as Ln,merge as ra,observableFrom as $n,once as ol,Subscription as ap}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as In,assertNonNullable as fi,combine as bi,ErrorCategory as Ue,filter as Js,filterChanged as kr,flattenObject as wr,fromEvent as Je,getTraceSubscriptionMethod as jh,interval as En,isNonNullable as Ar,isNullable as rl,map as gi,merge as _t,now as xn,Subject as Zs,Subscription as kn,tap as zh,throttle as sl,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as $h,ErrorCategory as Qu,Subject as ju}from"@vkontakte/videoplayer-shared/evergreen";var Ph=18,zu=!1;try{zu=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=Ph}catch(n){console.error(n)}var mn=class{constructor(e){this.bufferFull$=new ju;this.error$=new ju;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Qu.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};zu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Qu.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:$h(t)}}},Wu=mn;import{abortable as Tt,assertNonNullable as ke,ErrorCategory as Ot,fromEvent as Sn,getExponentialDelay as vn,isNonNullable as pi,isNullable as de,now as Ys,once as Vh,Subject as Ch,Subscription as Oh,ValueSubject as Ft}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Mh,throttleFn as Rh}from"@vkontakte/videoplayer-shared/evergreen";var qu=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??Mh({width:e,height:t});return u&&{id:n,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Gu=({id:n,bitrate:e})=>({id:n,bitrate:e}),Yu=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Ku=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),fn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),bn=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),gn=n=>"url"in n,$e=n=>n.type==="template";var Xu=n=>{n.sort((t,i)=>t.from-i.from);let e=[n[0]];for(let t=1;t<n.length;t++){let{from:i,to:r}=n[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(n[t])}return e},Ct=(n,e)=>{for(let t of n)if(e(t))return t;return null},Ju=n=>{let e=!1,t=Rh(()=>{e=!0},n);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Dh,Subscription as Bh}from"@vkontakte/videoplayer-shared/evergreen";var qs=n=>{let e=[];for(let t=0;t<n.length;t++){let i=Math.floor(n.start(t)*1e3),r=Math.ceil(n.end(t)*1e3);e.push(i,r)}return e};var Gs=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Bh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Dh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!D(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=qs(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],u=t[i+1];if(a>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var yr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ft(0);this.currentLowLatencySegmentLength$=new Ft(0);this.currentSegmentLength$=new Ft(0);this.onLastSegment$=new Ft(!1);this.fullyBuffered$=new Ft(!1);this.playingRepresentation$=new Ft(void 0);this.playingRepresentationInit$=new Ft(void 0);this.error$=new Ch;this.gaps=[];this.subscription=new Oh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Tt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wu(this.sourceBuffer),this.sourceBufferBufferedDiff=new Gs(this.mediaSource,this.sourceBuffer),this.subscription.add(Sn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Sn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ot.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!D(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,ii(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=se(this.sourceBuffer.buffered,u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,l<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ke(i,"No init buffer for starting representation"),ke(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Tt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();pi(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Tt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();pi(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Tt(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!$e(c.segmentReference))return;let h=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,h)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ke(r);let s=this.segments.get(i);ke(s,"No segments for starting representation");let a=this.initData.get(i);if(ke(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Tt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ke(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(de(u)||de(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),ke(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();pi(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!de(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||pi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);pi(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=se(this.sourceBuffer.buffered,e),h=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+a&&(s=h)}if(isFinite(this.bufferLimit)&&ii(this.sourceBuffer.buffered)>=this.bufferLimit){let c=se(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let h=o.at(0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o?.length&&se(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-se(this.sourceBuffer.buffered,e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;pi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!$e(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ke(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!$e(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+x||r<x&&m-p>=x||m<=i+x;return(d==="none"||d==="partially_ejected"&&g&&v&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(le(this.sourceBuffer.buffered,p)&&le(this.sourceBuffer.buffered,m)))&&g&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(u<=c||o<=h);d++){let p=a[d];if(u+=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,i="auto"){$e(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Tt(u,async function*(){let c=vn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ys(),!c)return;let h=new DataView(c),d=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(h,f)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(h,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(h);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Xe(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())$e(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Tt(a,async function*(){let o=vn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),Sn(window,"online").pipe(Vh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Ys(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Xe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if($e(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ys(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!$e(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ys();let h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Ke(a.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=o,c=l.byte.from-i,h=l.byte.to-i,d=h-c+1,p=c<r,m=h<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),b=o.loadedBytes===d?f:Ke(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",o.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(o.fedBytes+=b.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(le(this.sourceBuffer.buffered,e.segment.time.from,100)&&le(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ot.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",gn(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?Tt(this.destroyAbortController.signal,async function*(){let u=vn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,h=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,h);let d=c;this.isLive&&$e(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ot.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||de(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=u=>{if(s>=t)return;r.push({...u.time});let o=gn(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&o.status==="fed"&&a(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let d of h)["none","partially_ejected"].includes(d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let h={time:{from:o,to:l},url:"",status:"none"};a(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&a(l)}return r.length?(r=Xu(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||de(e)?0:se(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let a=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Ot.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||de(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=qs(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let c=0;c<e.length;c+=2){let h=e[c],d=e[c+1];o||(o=h-t<=a&&d+t>=u),(a>=h&&a<d-t||u>h+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ot.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as Tr,assertNever as Zu,fromEvent as el,merge as Fh,now as Ir,Subject as tl,ValueSubject as yn,flattenObject as mi,ErrorCategory as Er,SubscriptionRemovable as _h}from"@vkontakte/videoplayer-shared/evergreen";var Xs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new yn(void 0);this.lastConnectionReused$=new yn(void 0);this.lastRequestFirstBytes$=new yn(void 0);this.recoverableError$=new tl;this.error$=new tl;this.abortAllController=new AbortController;this.subscription=new _h;this.fetchManifest=Tr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ls(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Ks);return r?(t.log("success",mi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",mi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Tr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,h=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(c,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),c=S.toString();break}default:Zu(t)}this.requestQuic&&(c=vt(c));let p=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=Fh(el(this.abortAllController.signal,"abort"),el(a,"abort")).subscribe(()=>{try{S.abort()}catch(T){Ks(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(T){Ks(T)}p=S.signal}let f=Ir();d.log("startRequest",mi({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:f}));let b=yield this.doFetch(c,{priority:s,headers:h,signal:p}),g=Ir();if(!b)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){this.unsubscribeAbortSubscription(m);let S=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:S}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let S=Ir(),T={requestStartedAt:f,requestEndedAt:S,duration:S-f};return d.log("endRequest",mi(T)),d.end(),b.arrayBuffer()}let x=b.body;if(u){let S;[x,S]=b.body.tee(),this.throughputEstimator?.trackStream(S,o)}let v=x.getReader(),I,k=parseInt(b.headers.get("content-length")??"",10);Number.isFinite(k)&&(I=k),!I&&i&&(I=i.to-i.from+1);let L=0,P=I?new Uint8Array(I):new Uint8Array(0),E=!1,$=S=>{this.unsubscribeAbortSubscription(m),E=!0,Ks(S)},y=Tr(p,async function*({done:S,value:T}){if(L===0&&this.lastRequestFirstBytes$.next(Ir()-f),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!S&&T){if(l&&I)P.set(T,L),L+=T.byteLength;else{let z=new Uint8Array(P.length+T.length);z.set(P),z.set(T,P.length),P=z,L+=T.byteLength}r?.(new DataView(P.buffer),L),yield v?.read().then(y,$)}}.bind(this));yield v?.read().then(y,$),this.unsubscribeAbortSubscription(m);let O=Ir(),M={failed:E,requestStartedAt:f,requestEndedAt:O,duration:O-f};return E?(d.error("endRequest",mi(M)),d.end(),null):(d.log("endRequest",mi(M)),d.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=Tr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(a=Math.min(l,r),u=Math.max(c,s))),a=Math.min(a,0);let h=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!h)return null;let d=new DataView(h,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let p=t.parseInit(d),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(h,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(h),segments:b}}.bind(this));this.fetchTemplateRepresentation=Tr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=As(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Zu(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Er.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Er.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Er.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Er.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Er.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Ks=n=>{if(!Xe(n))throw n};import{isNullable as Nh,ValueSubject as Uh}from"@vkontakte/videoplayer-shared/evergreen";var xr=class n{constructor(e,t){this.currentRepresentation$=new Uh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Nh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&$e(t.segmentReference))}};var Wh=["progress","play","seeked","stalled","waiting"],qh=["timeupdate","progress","loadeddata","playing","seeked"];var ea=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new kn;this.representationSubscription=new kn;this.state$=new C("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new Zs;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new Zs;this.fetcherError$=new Zs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Zs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=In(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=In(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=ks(e??"",this.manifestUrlString)}catch(a){let u=Es(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(u)}if(!t)return null;let i=(a,u,o)=>!!(this.element?.canPlayType?.(u)&&Ae()?.isTypeSupported?.(`${u}; codecs="${o}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:u,streamIsUnpublished:o,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((u-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";l||(h=o?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let o=t.streams[a].filter(({mime:h,codecs:d})=>i(a,h,d)),l=new Set(o.map(({codecs:h})=>h)),c=Cs(l);if(c&&(r[a]=o.filter(({codecs:h})=>h.startsWith(c))),a==="video"){let h=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),p=r.video.some(m=>!m.hdr);B.display.isHDR&&h&&d?r.video=r.video.filter(m=>m.hdr):p&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",wr(s)),s}.bind(this));this.initRepresentations=In(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",wr({initialVideo:e,initialAudio:t,sourceHls:i})),fi(this.manifest),fi(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new kn,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Je(d,"error").pipe(Js(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?ts():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Yt())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new yr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Ar(t)){let d=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new yr("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}xr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new xr(this.manifest.streams.text,a)),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$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(_t(...qh.map(d=>Je(this.element,d))).pipe(gi(d=>this.element?se(this.element.buffered,this.element.currentTime*1e3):0),kr(),zh(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(_t(Je(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(kr()).subscribe(p=>this.liveStreamEndTimestamp=xn())),this.subscription.add(Je(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=En(1e3).subscribe(p=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Je(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(bi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(gi(({isActiveLive:p,isLowLatency:m})=>p&&m),kr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||ui(this.element,1)})),this.representationSubscription.add(bi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Js(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(bi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Js(({isLive:p})=>p),kr((p,m)=>m.bufferLength<p.bufferLength),gi(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(bi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>g&&(I=1+Math.sign(v)*x),ui(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(bi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(sl(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=pt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,k=isFinite(p)?p:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let E="none";if(L?E="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),E="active_low_latency"):b!==0&&k<x?E="live_forward_buffering":k<x+I&&(E="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),E==="live_forward_buffering"||E==="live_with_target_offset"){let $=d-(x+v),y=this.normolizeLiveOffset(Math.trunc(b+$/f)),O=Math.abs(y-b),M=0;!p||O<=this.tuning.dashCmafLive.offsetCalculationError?M=b:y>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(M=y),this.manifestUrlString=ee(this.manifestUrlString,M,2)}(E==="live_with_target_offset"||E==="live_forward_buffering")&&(d=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=_t(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(gi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=_t(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(gi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),h=bi({allBuffersFull:l,someBufferEnded:c}).pipe(kr(),gi(({allBuffersFull:d,someBufferEnded:p})=>d&&p),Js(d=>d));if(this.representationSubscription.add(_t(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(_t(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),$e(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Ar(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=En(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ue.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Xs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){fi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?xn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){fi(this.element),this.state$.setState("running");let e=Je(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(sl(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(_t(...Wh.map(t=>Je(this.element,t)),Je(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ue.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Je(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Je(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&le(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=xn(),a=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,h=l<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&c<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ue.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",wr(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=En(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){fi(this.element),fi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),le(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(rl(this.element)||rl(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",wr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ar(this.element)&&Ar(this.source)&&Ar(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=jh(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let o=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",wr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Gh,map as Yh,observeElementSize as Kh,Subscription as Xh,ValueSubject as wn,noop as Jh}from"@vkontakte/videoplayer-shared/evergreen";var ta=class{constructor(){this.subscription=new Xh;this.pipSize$=new wn(void 0);this.videoSize$=new wn(void 0);this.elementSize$=new wn(void 0);this.pictureInPictureWindowRemoveEventListener=Jh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Kh(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Gh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Yh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Nt=class{constructor(e){this.subscription=new ap;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new ti;this.stallsManager=new Qs;this.elementSizeManager=new ta;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return ep(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new hi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ve(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ea({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;sp(this.observableVideo)&&(this.observableVideo=Ie(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:al.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(An(h=>!!h.length),ol()).subscribe(h=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:h})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ln(h=>h.to.state!=="none"),ia());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(An(nl),ol()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ln(h=>h.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:h})=>{if(h==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(tp(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of d.audio){m.push(fn(f));let b=[];for(let g of f.representations){let x=Gu(g);b.push(x),this.audioTracksMap.set(x,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of d.video){p.push(bn(m));let f=[];for(let b of m.representations){let g=qu({...b,streamId:m.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(p);for(let m of d.text)for(let f of m.representations){let b=Yu(m,f);this.textTracksMap.set(b,{stream:m,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else h==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&Ju(u)||null;this.subscription.add(ra(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,rp(this.video,"progress")).pipe(An(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let h=this.player.state$.getState(),d=this.player.state$.getTransition();if(h!=="manifest_ready"&&h!=="running"||d||h==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=Ct(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);nl(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),h==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:h})=>{this.scene3D&&h&&this.scene3D.pointCameraTo(h.x,h.y)})),this.subscription.add(this.elementSizeManager.subscribe(h=>{this.scene3D&&h&&this.scene3D.setViewportSize(h.width,h.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ia()).subscribe(h=>{let d=Ct(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===h);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(bn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ia()).subscribe(h=>{let d=Ct(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===h);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(fn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(h=>{if(h?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(h),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ln(({to:h})=>h==="ready"),ia());this.subscription.add(ra(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,$n(["init"])).subscribe(()=>{let h=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:h?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ra(l,this.player.state$.stateChangeEnded$,$n(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=ra(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$n(["init"])).pipe(ip(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pi:$i,t=this.params.tuning.useNewAutoSelectVideoTrack?Ss:gs,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:bs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Ct(this.videoTracksMap.keys(),E=>E.id===u),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=Ct(this.videoStreamsMap.keys(),E=>E.id===c.id),d=h&&this.videoStreamsMap.get(h);if(!d)return;let p=se(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=g?.id&&Ct(this.audioStreamsMap.keys(),E=>E.id===g.id)||this.audioStreamsMap.keys().next().value,v=0;if(x){if(o&&!a){let E=e(o,d,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,E?.bitrate??-1/0)}if(l){let E=e(l,d,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,E?.bitrate??-1/0)}}let I=o;(a||!I)&&(I=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let k=x&&t(I,d,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=this.videoTracksMap.get(I)?.representation,P=k&&this.audioTracksMap.get(k)?.representation;L&&P?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=P):L&&!P&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:al.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ye(this.video),this.tracer.end()}};var Lr=class extends Nt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Pn,merge as ul,filter as ll,filterChanged as cl,isNullable as Mn,map as dl,ValueSubject as Rn,isNonNullable as np}from"@vkontakte/videoplayer-shared/evergreen";var $r=class extends Nt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Rn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(cl()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),h=!c.volume||c.muted;!o&&!l&&h?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(dl(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Pn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(dl(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(ll(o=>np(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(Pn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ul(r.playbackRateState$,new Rn(1))}).pipe(ll(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),h=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;h||l<1-d||this.video.paused||Mn(c)||(t=o-c)})).add(Pn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ul(r.playbackRateState$,new Rn(1))}).pipe(cl((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let h=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!h&&!this.video.paused&&c>=1-d||Mn(o)||Mn(l))return;let p=-1*(l-o-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=Ku(o);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var hl="X-Playback-Duration",Dn=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(hl)?parseInt(e.headers.get(hl),10):void 0};import{assertNever as gp,combine as Sp,debounce as vp,ErrorCategory as na,filter as yp,filterChanged as Tp,isNonNullable as fl,isNullable as oa,map as bl,merge as Ip,observableFrom as Ep,Subscription as xp,ValueSubject as Vn,VideoQuality as kp}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as op,getExponentialDelay as up}from"@vkontakte/videoplayer-shared/evergreen";var lp=n=>{let e=null;if(n.QUALITY&&(e=ft(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=op({width:t,height:i})}return e??null},cp=(n,e)=>{let t=n.split(`
178
+ `),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],u=a.match(/^#EXT-X-STREAM-INF:(.+)/),o=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let l=Object.fromEntries(u[1].split(",").map(b=>b.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,h=lp(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,g]=l.RESOLUTION.split("x").map(x=>parseInt(x,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();h&&i.push({id:c,quality:h,url:f,bandwidth:d,size:m,fps:p})}if(o){let l=Object.fromEntries(o[1].split(",").map(p=>{let m=p.indexOf("=");return[p.substring(0,m),p.substring(m+1)]}).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,d=l.NAME;c&&h&&r.push({type:"internal",id:h,label:d,language:h,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},dp=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Bn=0,pl=async(n,e=n,t,i)=>{let s=await(await fetch(n,i)).text();Bn+=1;try{let{qualityManifests:a,textTracks:u}=cp(s,e);return{qualityManifests:a,textTracks:u}}catch{if(Bn<=t.manifestRetryMaxCount)return await dp(up(Bn-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),pl(n,e,t)}return{qualityManifests:[],textTracks:[]}},sa=pl;import{isNonNullable as hp,Subscription as pp,throttle as mp,ValueSubject as ml,Subject as fp,ErrorCategory as bp}from"@vkontakte/videoplayer-shared/evergreen";var aa=class{constructor(e,t,i,r,s){this.subscription=new pp;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ml(null);this.getCurrentTime$=new ml(null);this.error$=new fp;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(mp(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(a,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
179
+ `),s=0;for(let a=0;a<r.length;++a){let u=r[a];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++a],l=new URL(o,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let h=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-h}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(hp(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:bp.WTF,thrown:t,message:e})}};var Pr=class{constructor(e){this.subscription=new xp;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Vn([]);this.liveOffset=new Pt;this.manifestStartTime$=new Vn(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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 r?.to==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gp(t)}};this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kp.INVARIANT,url:this.params.source.url};let t=(i,r)=>sa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new aa(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:na.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:na.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Vn(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:na.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(Tp(),bl(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&fl(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(p=>p.id===h);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(ue(d.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(Sp({startTime:this.manifestStartTime$.pipe(yp(fl)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(bl(u=>u.map(({id:o,quality:l,size:c,bandwidth:h,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Ip(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ep(["init"])).pipe(vp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if(oa(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:o}=t?.to??i??{};for(let[l,c]of[[u,"mq"],[o,"lq"]]){let h=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Dn(a).then(u=>{if(!oa(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(oa(o)||!isFinite(o))&&fetch(a).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let h=new URL(c,a).toString();Dn(h).then(d=>{oa(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:na.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ee(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as wp,debounce as Ap,ErrorCategory as Cn,fromEvent as On,isNonNullable as Lp,isNullable as $p,map as gl,merge as Sl,observableFrom as vl,Subscription as Pp,ValueSubject as Mp,VideoQuality as Rp}from"@vkontakte/videoplayer-shared/evergreen";var Mr=class{constructor(e){this.subscription=new Pp;this.videoState=new C("stopped");this.manifests$=new Mp([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:h*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wp(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Rp.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),sa(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Cn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:Cn.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(gl(u=>u.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Lp(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ue(m.url)))}let h=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(h!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(h),p.playbackRate=h)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe(gl(u=>u.map(({id:o,quality:l,size:c,bandwidth:h,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Sl(On(u,"addtrack"),On(u,"removetrack"),On(u,"change"),vl(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let a=Sl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,vl(["init"])).pipe(Ap(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if($p(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Dp,assertNonNullable as yl,debounce as Bp,ErrorCategory as Tl,isHigherOrEqual as Vp,isLowerOrEqual as Cp,isNonNullable as Op,merge as Fp,observableFrom as _p,Subscription as Np,map as Up}from"@vkontakte/videoplayer-shared/evergreen";var Rr=class{constructor(e){this.subscription=new Np;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return Dp(e)}};this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:Tl.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Up(u=>u.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&Op(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(o),c.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let a=Fp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,_p(["init"])).pipe(Bp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;yl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];yl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=vt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=Ye(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||Kt(e,a[0].quality,a.at(-1)?.quality)){i();return}let u=e.max?Cp(r,e.max):!0,o=e.min?Vp(r,e.min):!0;u&&o||i(e)}};import{assertNever as El,debounce as zp,merge as xl,observableFrom as Wp,Subscription as qp,map as kl,ValueSubject as Gp,ErrorCategory as _n,VideoQuality as Yp}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Hp}from"@vkontakte/videoplayer-shared/evergreen";var Il=["stun:videostun.mycdn.me:80"],Qp=1e3,jp=3,Fn=()=>null,ua=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=Fn;this.externalStopCallback=Fn;this.externalErrorCallback=Fn;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{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:Il}]};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:Hp.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){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),Qp)}normalizeOptions(e={}){let t={stunServerList:Il,maxRetryNumber:jp,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Dr=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new Gp(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return El(e)}};this.subscription=new qp,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ve(e.container,e.tuning),this.liveStreamClient=new ua(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:_n.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(xl(this.videoState.stateChangeStarted$.pipe(kl(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(kl(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(a)}`})}));let r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(a,u)=>this.subscription.add(a.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),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(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Te(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 El(a.to)}},i)).add(xl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Wp(["init"])).pipe(zp(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(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:Yp.INVARIANT}),this.video.srcObject=e,w(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:_n.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_n.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Br=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Vr,assertNonNullable as It,ErrorCategory as la,filter as Ml,isNonNullable as Rl,isNullable as im,map as rm,merge as sm,once as am,Subject as ae,Subscription as Dl,ValueSubject as _,flattenObject as Nn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Kp,map as wl,Subscription as Xp,Subject as Jp}from"@vkontakte/videoplayer-shared/evergreen";var Al=n=>new Kp(e=>{let t=new Xp,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(wl(({from:l,to:c})=>`${l}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,s=n.providerChanged$.pipe(wl(({type:l})=>l!==void 0)),a=new Jp,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>a.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>a.next(o),n.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as Zp,Subscription as em,combine as tm,filter as $l,once as Pl}from"@vkontakte/videoplayer-shared/evergreen";function Ll(){return new(window.AudioContext||window.webkitAudioContext)}var Si=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new em;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe($l(s=>!!s.type),Pl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(tm({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe($l(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Pl()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ll();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:Zp.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var nm={chunkDuration:5e3,maxParallelRequests:5},Cr=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ae;this.noAvailableProvidersError$=new ae;this.volumeMultiplierError$=new ae;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ae,fetcherError$:new ae,fetcherRecoverableError$:new ae,warning$:new ae,willSeekEvent$:new ae,soundProhibitedEvent$:new ae,seekedEvent$:new ae,loopedEvent$:new ae,endedEvent$:new ae,firstBytesEvent$:new ae,loadedMetadataEvent$:new ae,firstFrameEvent$:new ae,canplay$:new ae,isLive$:new _(void 0),isLiveEnded$:new _(null),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ae,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new Dl;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=wu([...Lu(this.params.tuning),...Au(this.params.tuning)],this.params.tuning).filter(l=>Rl(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Nn(s)),this.screenFormatsIterator=new Br(s);let a=[...Xa(!0),...Xa(!1)];this.chromecastFormatsIterator=new Br(a.filter(l=>Rl(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Si.isSupported()&&(this.volumeMultiplierManager=new Si(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}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(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(im(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:la.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination: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"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Vr(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,u={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return It(o),this.params.tuning.useNewDashProvider?new Lr({...u,source:o,sourceHls:l}):new Sr({...u,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),this.params.tuning.useNewDashProvider?new $r({...u,source:o}):new vr({...u,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return It(o),new Mr({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return It(o),new Pr({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return It(o),new Rr({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new eu({...u,source:o,config:{...nm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return It(o),new Dr({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Vr(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return It(u),new Ei({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:a,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 Vr(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Vr(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 Vr(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);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:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Dl,t=!1,i=0;return e.add(sm(this.providerOutput.error$.pipe(Ml(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Al({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(rm(r=>({id:`ProviderHangup:${r}`,category:la.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Ml(({to:s})=>s==="playing"),am()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===la.NETWORK,o=r.category===la.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o,h=l&&!o&&(u&&t||!c);a={...a,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Nn(a)):this.tracer.error("providerError",Nn(a))})),e}};import{fromEvent as ca,once as om,combine as um,Subscription as Bl,ValueSubject as Un,map as lm,filter as cm,isNonNullable as da,now as Pe,safeStorage as Hn}from"@vkontakte/videoplayer-shared/evergreen";var dm=5e3,Vl="one_video_throughput",Cl="one_video_rtt",Or=window.navigator.connection,Ol=()=>{let n=Or?.downlink;if(da(n)&&n!==10)return n*1e3},Fl=()=>{let n=Or?.rtt;if(da(n)&&n!==3e3)return n},_l=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Qn=class n{constructor(e){this.subscription=new Bl;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Vl)||(e.useBrowserEstimation?Ol():void 0)||dm,i=n.load(Cl)??(e.useBrowserEstimation?Fl():void 0)??0;if(this.throughput$=new Un(t),this.rtt$=new Un(i),this.rttAdjustedThroughput$=new Un(_l(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Ol();a&&this.throughput.next(a);let u=Fl();da(u)&&this.rtt.next(u)};Or&&"onchange"in Or&&this.subscription.add(ca(Or,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Hn.set(Vl,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Hn.set(Cl,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(um({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(lm(({throughput:r,rtt:s})=>_l(r,s,e.rttPenaltyRequestSize)),cm(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Pe(),r=new Bl;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(ca(e,"progress").pipe(om()).subscribe(s=>{t=s.loaded,i=Pe()}));break;case 1:case 0:r.add(ca(e,"loadstart").subscribe(()=>{t=0,i=Pe()}));break}r.add(ca(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=Pe(),o=a-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Pe(),a=0,u=Pe(),o=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:h})=>{if(c)!t&&this.addRawSpeed(r,Pe()-s,1),this.concurrentDownloads.delete(e);else if(h){if(t){let d=Pe();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(a,m,1,t),a=h.byteLength,s=Pe()}else a+=h.byteLength;u=Pe()}else r+=h.byteLength,a+=h.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Pe()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Pe()-u,this.concurrentDownloads.size),a=0,u=Pe());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Hn.get(e);if(da(t))return parseInt(t,10)??void 0}},Nl=Qn;import{fillWithDefault as hm,VideoQuality as ha}from"@vkontakte/videoplayer-shared/evergreen";var Ul={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:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:ha.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ha.Q_720P,trafficSavingLimit:ha.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ha.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},Hl=n=>({...hm(n,Ul),configName:[...n.configName??[],...Ul.configName]});import{assertNonNullable as pa,combine as ut,ErrorCategory as ma,filter as V,filterChanged as W,fromEvent as zn,isNonNullable as Wl,isNullable as vm,Logger as ym,map as j,mapTo as ql,merge as Et,now as fa,once as U,Subject as q,Subscription as Gl,tap as Wn,ValueSubject as A,isHigher as Tm,isInvariantQuality as Yl,flattenObject as xt,throttle as qn,getTraceSubscriptionMethod as Kl,TracerFactory as Im,InternalsExposure as Em}from"@vkontakte/videoplayer-shared/evergreen";import{merge as pm,map as mm,filter as Ql,isNonNullable as fm}from"@vkontakte/videoplayer-shared/evergreen";var jn=({seekState:n,position$:e})=>pm(n.stateChangeEnded$.pipe(mm(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Ql(fm)),e.pipe(Ql(()=>n.getState().state==="none")));import{assertNonNullable as bm}from"@vkontakte/videoplayer-shared/evergreen";var jl=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return bm(e,`Wrong container or containerId {${n.container}}`),e};import{filter as gm,once as Sm}from"@vkontakte/videoplayer-shared/evergreen";var zl=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(gm(r=>r.length>0),Sm()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var ba=class{constructor(e={configName:[]},t=Im.createRootTracer(!1)){this.subscription=new Gl;this.logger=new ym;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new A(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new A(void 0),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),predefinedQualityLimitType$:new A("unknown"),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),isLiveEnded$:new A(null),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new q,ready$:new q,started$:new q,playing$:new q,paused$:new q,stopped$:new q,willReady$:new q,willStart$:new q,willResume$:new q,willPause$:new q,willStop$:new q,willDestruct$:new q,watchCoverageRecord$:new q,watchCoverageLive$:new q,managedError$:new q,fatalError$:new q,fetcherRecoverableError$:new q,ended$:new q,looped$:new q,seeked$:new q,willSeek$:new q,autoplaySoundProhibited$:new q,firstBytes$:new q,loadedMetadata$:new q,firstFrame$:new q,canplay$:new q,log$:new q,fetcherError$:new q,severeStallOccured$:new q};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Mo,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=Hl(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Yr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Nl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Em("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let a=Reflect.get(i,r,s);return typeof a!="function"?a:(...u)=>{try{return a.apply(i,u)}catch(o){let l=u.map(d=>JSON.stringify(d,(p,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),c=`Player.${String(r)}`,h=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:ma.WTF,message:h,thrown:o}),o}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",xt(a)),this.domContainer=jl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Cr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?B.isInited$.pipe(V(s=>!!s),U()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),zn(document,"visibilitychange").pipe(U()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{pa(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),U()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",xt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{pa(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",xt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{zl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(vm(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Wl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ba(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),U()).subscribe(()=>{this.initedAt=fa(),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"ready":this.events.willReady$.next();break;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 a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",xt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:ma.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(U()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",xt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(a=>a.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ut({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:a,currentVideoStream:u})=>a.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>Yl(o)?1:Yl(l)?-1:Tm(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let u={};for(let o of a)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(V(a=>Wl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(W((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).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(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(j(a=>a?{start:a.from,end:a.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.isLiveEnded$.pipe(Wn(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).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(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ut({hasLiveOffsetByPaused:Et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(a=>a.to),W(),j(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(ut({atLiveEdge:ut({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:jn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:a,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return a&&Math.abs(u)<l/1e3}),W(),Wn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:a,hasPausedTimeoutCase:u})=>a&&!u)).subscribe(this.info.atLiveEdge$)).add(ut({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:a,position:u,duration:o})=>a&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),W(),Wn(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(a=>a.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(a=>a.volume),W()).subscribe(this.info.volume$)).add(jn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Et(e.providerOutput.endedEvent$.pipe(ql(!0)),e.providerOutput.seekedEvent$.pipe(ql(!1))).pipe(W()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(j(a=>({id:a?`No${a}`:"NoProviders",category:ma.VIDEO_PIPELINE,message:a?`${a} 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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(U(),j(a=>a??fa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(U(),j(()=>fa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(U(),j(()=>fa()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new A(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:a})=>a==="playing"),U()).subscribe(()=>i.next(!1)));let r=0,s=Et(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let a=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return a&&!u}),W());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Et(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Et(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),h;c==="CONNECTED"?h="second_screen":o?l?a?h="pip":u?h="fullscreen":h="inline":h="invisible":h="none",this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(j(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Gl;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),U()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ye(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput: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(Et(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;pa(this.providerContainer),pa(e),Po(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>$o(t)),this.providerContainer.current$.subscribe(({type:t})=>Li("provider",t)),e.duration$.subscribe(t=>Li("duration",t)),e.availableVideoTracks$.pipe(V(t=>!!t.length),U()).subscribe(t=>Li("tracks",t)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(j(t=>t?.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(t=>this.subscription.add(t)),Li("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=Kl(this.tracer.log.bind(this.tracer)),t=Kl(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(W()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ut({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(i=>i>0),W()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ut({currentBuffer:this.info.currentBuffer$.pipe(V(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(qn(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(ut({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),qn(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),V(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),V(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),V(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ut({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:i,rtt:r})=>!!i&&!!r),qn(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),V(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:ma.DOM,message:String(r)})})};this.subscription.add(Et(zn(document,"visibilitychange"),zn(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",xt({quality:t,availableTracks:xt(e),track:xt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Vi()}};import{Subscription as sD,Observable as aD,Subject as nD,ValueSubject as oD,VideoQuality as uD}from"@vkontakte/videoplayer-shared/evergreen";var lD=`@vkontakte/videoplayer-core@${Yn}`;export{Wr as ChromecastState,va as HttpConnectionType,aD as Observable,Se as PlaybackState,ba as Player,qr as PredefinedQualityLimits,lD as SDK_VERSION,nD as Subject,sD as Subscription,ya as Surface,Yn as VERSION,oD as ValueSubject,et as VideoFormat,uD as VideoQuality,B as clientChecker,Ai as isMobile};