@vkontakte/videoplayer-core 2.0.103 → 2.0.104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +73 -27
- package/es2015.esm.js +72 -26
- package/es2018.cjs.js +73 -27
- package/es2018.esm.js +72 -26
- package/esnext.cjs.js +75 -29
- package/esnext.esm.js +73 -27
- package/evergreen.esm.js +73 -27
- package/package.json +7 -7
- package/types/enums/AndroidPreferredFormat.d.ts +8 -0
- package/types/enums/WebmCodecStrategy.d.ts +7 -0
- package/types/env.d.ts +1 -0
- package/types/index.d.ts +12 -0
- package/types/player/Player.d.ts +173 -0
- package/{index.d.ts → types/player/types.d.ts} +64 -391
- package/types/player/utils/optimisticPosition.d.ts +12 -0
- package/types/player/utils/selectContainer.d.ts +3 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +31 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +23 -0
- package/types/providers/ChromecastProvider/index.d.ts +33 -0
- package/types/providers/DashLiveProvider/DashLiveProvider.d.ts +37 -0
- package/types/providers/DashLiveProvider/index.d.ts +2 -0
- package/types/providers/DashLiveProvider/types.d.ts +21 -0
- package/types/providers/DashLiveProvider/utils/FilesFetcher.d.ts +25 -0
- package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +143 -0
- package/types/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +33 -0
- package/types/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +42 -0
- package/types/providers/DashProvider/baseDashProvider.d.ts +52 -0
- package/types/providers/DashProvider/consts.d.ts +1 -0
- package/types/providers/DashProvider/dashCmafLiveProvider.d.ts +8 -0
- package/types/providers/DashProvider/dashProvider.d.ts +6 -0
- package/types/providers/DashProvider/index.d.ts +2 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +103 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +51 -0
- package/types/providers/DashProvider/lib/parsers/mpd.d.ts +3 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxModel.d.ts +20 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxParser.d.ts +21 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxTypeEnum.d.ts +26 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/box.d.ts +79 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/equi.d.ts +21 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/ftyp.d.ts +17 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +22 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdat.d.ts +15 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mfhd.d.ts +11 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/prhd.d.ts +16 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sidx.d.ts +48 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/st3d.d.ts +23 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfdt.d.ts +17 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfhd.d.ts +22 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tkhd.d.ts +42 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trun.d.ts +31 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/unknown.d.ts +6 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +6 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/fullBox.d.ts +15 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/isobmff.d.ts +12 -0
- package/types/providers/DashProvider/lib/parsers/webm/ebml.d.ts +76 -0
- package/types/providers/DashProvider/lib/parsers/webm/webm.d.ts +3 -0
- package/types/providers/DashProvider/lib/player.d.ts +75 -0
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +18 -0
- package/types/providers/DashProvider/lib/types.d.ts +156 -0
- package/types/providers/DashProvider/lib/utils.d.ts +14 -0
- package/types/providers/HlsJsProvider/index.d.ts +24 -0
- package/types/providers/HlsLiveProvider/index.d.ts +30 -0
- package/types/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +3 -0
- package/types/providers/HlsProvider/index.d.ts +21 -0
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +21 -0
- package/types/providers/MpegProvider/index.d.ts +20 -0
- package/types/providers/ProviderContainer/index.d.ts +42 -0
- package/types/providers/ProviderContainer/types.d.ts +20 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +20 -0
- package/types/providers/ProviderContainer/utils/playbackHangup.d.ts +12 -0
- package/types/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +188 -0
- package/types/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +60 -0
- package/types/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +9 -0
- package/types/providers/types.d.ts +83 -0
- package/types/providers/utils/HTMLVideoElement/DroppedFramesManager.d.ts +44 -0
- package/types/providers/utils/HTMLVideoElement/TextTrackManager.d.ts +30 -0
- package/types/providers/utils/HTMLVideoElement/clear.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/destroy.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/forcePlay.d.ts +7 -0
- package/types/providers/utils/HTMLVideoElement/observable.d.ts +25 -0
- package/types/providers/utils/HTMLVideoElement/pool.d.ts +2 -0
- package/types/providers/utils/HTMLVideoElement/surface.d.ts +2 -0
- package/types/providers/utils/LiveOffset/index.d.ts +14 -0
- package/types/providers/utils/LiveOffset/types.d.ts +10 -0
- package/types/providers/utils/addQuicParam.d.ts +2 -0
- package/types/providers/utils/extractConnectionHeaders.d.ts +6 -0
- package/types/providers/utils/generateLiveUrl.d.ts +9 -0
- package/types/providers/utils/okQualityStringToVideoQuality.d.ts +3 -0
- package/types/providers/utils/parseFps.d.ts +1 -0
- package/types/providers/utils/syncDesiredState.d.ts +12 -0
- package/types/providers/utils/syncPlaybackState.d.ts +4 -0
- package/types/utils/3d/Camera3D.d.ts +14 -0
- package/types/utils/3d/CameraRotationManager.d.ts +62 -0
- package/types/utils/3d/Scene3D.d.ts +132 -0
- package/types/utils/3d/types.d.ts +25 -0
- package/types/utils/StateMachine/StateMachine.d.ts +19 -0
- package/types/utils/StateMachine/types.d.ts +60 -0
- package/types/utils/StatefulIterator/index.d.ts +13 -0
- package/types/utils/ThroughputEstimator.d.ts +25 -0
- package/types/utils/addScript.d.ts +2 -0
- package/types/utils/autoSelectVideoTrack.d.ts +26 -0
- package/types/utils/buffer/getBufferedRangeForPosition.d.ts +3 -0
- package/types/utils/buffer/getForwardBufferDuration.d.ts +3 -0
- package/types/utils/buffer/getTotalBufferDuration.d.ts +3 -0
- package/types/utils/buffer/isPositionBuffered.d.ts +3 -0
- package/types/utils/changePlaybackRate.d.ts +2 -0
- package/types/utils/hostnameFromUrl.d.ts +2 -0
- package/types/utils/isInPiP.d.ts +1 -0
- package/types/utils/link.d.ts +2 -0
- package/types/utils/mediaSource.d.ts +8 -0
- package/types/utils/observeElementVisibility.d.ts +3 -0
- package/types/utils/playbackTelemetry.d.ts +12 -0
- package/types/utils/setStateWithSubscribe.d.ts +3 -0
- package/types/utils/smoothedValue/baseSmoothedValue.d.ts +18 -0
- package/types/utils/smoothedValue/emaAndMaSmoothedValue.d.ts +7 -0
- package/types/utils/smoothedValue/emaTopExtremumValue.d.ts +10 -0
- package/types/utils/smoothedValue/smoothedValueFactory.d.ts +6 -0
- package/types/utils/smoothedValue/twoEmaSmoothedValue.d.ts +8 -0
- package/types/utils/smoothedValue/types.d.ts +26 -0
- package/types/utils/smoothedValue/utils.d.ts +3 -0
- package/types/utils/tuningConfig.d.ts +164 -0
- package/types/utils/videoFormat.d.ts +2 -0
package/evergreen.esm.js
CHANGED
|
@@ -1,46 +1,92 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.104
|
|
3
|
+
* Mon, 24 Jun 2024 13:01:09 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as g,Subject as x,Subscription as ee,isNonNullable as A,ErrorCategory as P,isNullable as Q,fromEvent as C,assertNever as V,merge as O,tap as Nt,map as T,observableFrom as Ce,filterChanged as de,assertNonNullable as v,debounce as Ge,getHighestQuality as vs,timeout as Es,getCurrentBrowser as $i,CurrentClientBrowser as is,combine as Le,once as Se,mapTo as Xt,filter as oe,VideoQuality as ke,now as ae,assertNotEmptyArray as As,videoSizeToQuality as dt,isInvariantQuality as ut,isHigher as $t,isLower as Qt,isHigherOrEqual as gi,isLowerOrEqual as Kt,interval as Bt,Observable as ki,videoQualityToHeight as $s,abortable as Te,getExponentialDelay as jt,throttle as ks,observeElementSize as ws,isIOS as Ps,CurrentClientDevice as Ds,safeStorage as li,fillWithDefault as Ls,Logger as xs}from"@vkontakte/videoplayer-shared/evergreen.esm.js";import{Observable as Zr,Subject as en,Subscription as tn,ValueSubject as sn,VideoQuality as an}from"@vkontakte/videoplayer-shared/evergreen.esm.js";const Cs="2.0.103";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var m;(function(a){a.MPEG="MPEG",a.DASH="DASH_SEP",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(m||(m={}));var ge;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ge||(ge={}));var pe;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(pe||(pe={}));var Si;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Si||(Si={}));var G;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(G||(G={}));var We;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible"})(We||(We={}));var Rs=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Is{connection$=new g(void 0);castState$=new g(pe.NOT_AVAILABLE);errorEvent$=new x;contentId;realCastState$=new g(pe.NOT_AVAILABLE);subscription=new ee;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;const i=A(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},s||Rs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:P.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){A(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Q(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Q(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(C(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return V(s.sessionState)}})).add(O(C(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nt(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),T(s=>s.castState)),Ce([i.getCastState()])).pipe(de(),T(Bs),Nt(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const r=s===pe.CONNECTED,n=A(this.connection$.getValue());if(r&&!n){const o=i.getCurrentSession();v(o);const d=o.getCastDevice(),c=o.getMediaSession()?.media.contentId;(Q(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:d}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===pe.CONNECTED?A(this.connection$.getValue())?pe.CONNECTED:pe.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:P.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Bs=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return pe.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return pe.AVAILABLE;case cast.framework.CastState.CONNECTING:return pe.CONNECTING;case cast.framework.CastState.CONNECTED:return pe.CONNECTED;default:return V(a)}};var le;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(le||(le={}));var Oe=(a,e=0,t=le.OFFSET_P)=>{switch(t){case le.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case le.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case le.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:V(t)}return a};const Ii=(a,e)=>{switch(e){case le.OFFSET_P:return NaN;case le.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case le.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:V(e)}};var R=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class ne{state;prevState;transition;transitionStarted$=new x;transitionEnded$=new x;transitionUpdated$=new x;forceChanged$=new x;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||A(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Ms=a=>{switch(a){case m.MPEG:case m.DASH_SEP:case m.DASH_ONDEMAND:case m.DASH_WEBM:case m.DASH_WEBM_AV1:case m.HLS:case m.HLS_ONDEMAND:return!1;case m.DASH_LIVE:case m.DASH_LIVE_CMAF:case m.HLS_LIVE:case m.HLS_LIVE_CMAF:case m.DASH_LIVE_WEBM:case m.WEB_RTC_LIVE:return!0;default:return V(a)}};var F;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(F||(F={}));const _s=5,Os=5,Ns=500,Bi=7e3;class Fs{subscription=new ee;loadMediaTimeoutSubscription=new ee;videoState=new ne(F.STOPPED);params;log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ms(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ee;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(T(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(T(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,r)=>this.subscription.add(s.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new x;e.add(s.pipe(Ge(Ns)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===G.Applying||Math.abs(o-r)>_s)&&s.next(o),r=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:r}=this.params.connection,n=s.value,o=this.params.output.isBuffering$.getValue(),d=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&r.duration-r.currentTime<Os&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,l.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:V(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(F.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(F.PLAYING),R(this.params.desiredState.playbackState,l.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:G.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),R(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&R(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,r;switch(e){case m.MPEG:{const c=t[e];v(c);const u=vs(Object.keys(c));v(u);const h=c[u];v(h),i=h,s="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case m.HLS:case m.HLS_ONDEMAND:{const c=t[e];v(c),i=c.url,s="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case m.DASH_SEP:case m.DASH_ONDEMAND:case m.DASH_WEBM:case m.DASH_WEBM_AV1:{const c=t[e];v(c),i=c.url,s="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case m.DASH_LIVE_CMAF:{const c=t[e];v(c),i=c.url,s="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case m.HLS_LIVE:case m.HLS_LIVE_CMAF:{const c=t[e];v(c),i=Oe(c.url),s="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case m.DASH_LIVE:case m.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",u=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:P.VIDEO_PIPELINE,message:c,thrown:u}),u}case m.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);n.contentUrl=i,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:d}=this.params.meta;return A(o)&&(n.metadata.title=o),A(d)&&(n.metadata.subtitle=d),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===G.Applying||i.state===G.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,r)=>{this.loadMediaTimeoutSubscription.add(Es(Bi).subscribe(()=>r(`timeout(${Bi})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===G.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:P.VIDEO_PIPELINE,message:r,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!t){if(s?.to!==l.PAUSED&&r.state===G.Requested&&e!==F.STOPPED){this.seek(r.position/1e3);return}switch(i){case l.READY:{switch(e){case F.PLAYING:case F.PAUSED:case F.READY:break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:V(e)}break}case l.PLAYING:{switch(e){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:V(e)}break}case l.PAUSED:{switch(e){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:V(e)}break}default:V(i)}}}}const wi=a=>{a.removeAttribute("src"),a.load()},Vs=a=>{try{a.pause(),a.playbackRate=0,wi(a),a.remove()}catch(e){console.error(e)}};class Us{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const bi=window.WeakMap?new WeakMap:new Us,lt=a=>{let e=a.querySelector("video");const t=!!e;return e?wi(e):(e=document.createElement("video"),a.appendChild(e)),bi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ft=a=>{const e=bi.get(a);bi.delete(a),e?wi(a):Vs(a)},Qe=(a,e,t,{equal:i=(n,o)=>n===o,changed$:s,onError:r}={})=>{const n=a.getState(),o=e(),d=Q(s),c=new ee;return s&&c.add(s.subscribe(u=>{const h=a.getState();i(u,h)&&a.setState(u)},r)),i(o,n)||(t(n),d&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(u=>{t(u.to),d&&a.setState(u.to)},r)),c},Vt=(a,e,t)=>Qe(e,()=>a.loop,i=>{A(i)&&(a.loop=i)},{onError:t}),pt=(a,e,t,i)=>Qe(e,()=>({muted:a.muted,volume:a.volume}),s=>{A(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,r)=>s===r||s?.muted===r?.muted&&s?.volume===r?.volume,changed$:t,onError:i}),Pt=(a,e,t,i)=>Qe(e,()=>a.playbackRate,s=>{A(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),Hs=a=>["__",a.language,a.label].join("|"),Ys=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class it{available$=new x;current$=new g(void 0);error$=new x;video;cueSettings;subscription=new ee;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=r=>{this.error$.next({id:"TextTracksManager",category:P.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Qe(t.internalTextTracks,()=>Object.values(this.internalTracks),r=>{A(r)&&this.setInternal(r)},{equal:(r,n)=>A(r)&&A(n)&&r.length===n.length&&r.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(T(r=>r.filter(({type:n})=>n==="internal"))),onError:s})),this.subscription.add(Qe(t.externalTextTracks,()=>Object.values(this.externalTracks),r=>{A(r)&&this.setExternal(r)},{equal:(r,n)=>A(r)&&A(n)&&r.length===n.length&&r.every(({id:o},d)=>o===n[d].id),changed$:this.available$.pipe(T(r=>r.filter(({type:n})=>n==="external"))),onError:s})),this.subscription.add(Qe(t.currentTextTrack,()=>{if(this.video)return;const r=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return r&&this.htmlTextTrackToITextTrack(r).id},r=>this.select(r),{changed$:this.current$,onError:s})),this.subscription.add(Qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){v(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(O(C(e,"addtrack"),C(e,"removetrack"),Ce(["init"])).pipe(T(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),de((i,s)=>i.length===s.length&&i.every(({id:r},n)=>r===s[n].id))).subscribe(this.available$)),this.subscription.add(O(C(e,"change"),Ce(["init"])).pipe(T(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),T(i=>i&&this.htmlTextTrackToITextTrack(i).id),de()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(C(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(C(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;A(t.align)&&(s.align=t.align),A(t.position)&&(s.position=t.position),A(t.size)&&(s.size=t.size),A(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){v(this.video);const t=[...this.video.textTracks];return e?t:t.filter(it.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:Hs(e),r=this.externalTracks.has(s),n=s.includes("auto");return r?{id:s,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:r})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===s&&n.isAuto===r)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){v(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!Ys(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){v(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){v(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class Pi{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const ss=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Mi=a=>{const e=ss(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Gs=a=>{const e=ss(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},qs=3;var zs=(a,e,t=qs)=>{let i=0,s=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(i=n,s=o,!t)return{from:i,to:s};for(let d=r-1;d>=0;d--)a.end(d)+t>=i&&(i=a.start(d));for(let d=r+1;d<a.length;d++)a.start(d)-t<=s&&(s=a.end(d))}}return{from:i,to:s}};const mt=a=>{const e=M=>C(a,M).pipe(Xt(void 0)),i=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>C(a,M))).pipe(T(M=>M.type==="ended"?a.readyState<2:a.readyState<3),de()),s=O(C(a,"progress"),C(a,"timeupdate")).pipe(T(()=>zs(a.buffered,a.currentTime))),n=$i().browser===is.Safari?Le({play:e("play").pipe(Se()),playing:e("playing")}).pipe(Xt(void 0)):e("playing"),o=C(a,"volumechange").pipe(T(()=>({muted:a.muted,volume:a.volume}))),d=C(a,"ratechange").pipe(T(()=>a.playbackRate)),c=C(a,"error").pipe(oe(()=>!!(a.error||a.played.length)),T(()=>{const M=a.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:P.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:a.error??void 0}})),u=C(a,"timeupdate").pipe(T(()=>a.currentTime)),h=new x,p=.3;let f;u.subscribe(M=>{a.loop&&A(f)&&A(M)&&f>=a.duration-p&&M<=p&&h.next(f),f=M});const S=C(a,"enterpictureinpicture"),w=C(a,"leavepictureinpicture"),y=new g(Gs(a));S.subscribe(()=>y.next(!0)),w.subscribe(()=>y.next(!1));const $=new g(Mi(a));return C(a,"fullscreenchange").pipe(T(()=>Mi(a))).subscribe($),{playing$:n,pause$:e("pause").pipe(oe(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:C(a,"durationchange").pipe(T(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:o,playbackRateState$:d,inPiP$:y,inFullscreen$:$}};var ai=a=>{switch(a){case"mobile":return ke.Q_144P;case"lowest":return ke.Q_240P;case"low":return ke.Q_360P;case"sd":case"medium":return ke.Q_480P;case"hd":case"high":return ke.Q_720P;case"fullhd":case"full":return ke.Q_1080P;case"quadhd":case"quad":return ke.Q_1440P;case"ultrahd":case"ultra":return ke.Q_2160P}};let Di=!1,je={};const Ws=a=>{Di=a},Qs=()=>{je={}},js=a=>{a(je)},zt=(a,e)=>{Di&&(je.meta=je.meta??{},je.meta[a]=e)};class Ue{name;constructor(e){this.name=e}next(e){if(!Di)return;je.series=je.series??{};const t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}}var ot;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(ot||(ot={}));const Js=new Ue("best_bitrate"),Xs=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Ks{last;history={};recordSelection(e){this.history[e.id]=ae()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Zs='Assertion "ABR Tracks is empty array" failed',ri=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:d,history:c,droppedVideoMaxQualityLimit:u,abrLogger:h})=>{As(a,Zs);const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},S=f&&dt(f),w=i.considerPlaybackRate&&A(o)?o:1,y=a.filter(L=>!ut(L.quality)).sort((L,I)=>$t(L.quality,I.quality)?-1:1),$=y.at(-1)?.quality,_=y.at(0)?.quality,M=Q(s)||A(s.min)&&A(s.max)&&Qt(s.max,s.min)||A(s.min)&&_&&$t(s.min,_)||A(s.max)&&$&&Qt(s.max,$),E=w*Xs(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},q=y.filter(L=>(S?Qt(L.quality,S):!0)?(A(t)&&isFinite(t)&&A(L.bitrate)?t-r>=L.bitrate*E:!0)?i.lazyQualitySwitch&&A(i.minBufferToSwitchUp)&&d&&!ut(d.quality)&&(n??0)<i.minBufferToSwitchUp&&$t(L.quality,d.quality)?(D[L.quality]=ot.Buffer,!1):!!u&&gi(L.quality,u)?(D[L.quality]=ot.DroppedFramesLimit,!1):M||(Q(s.max)||Kt(L.quality,s.max))&&(Q(s.min)||gi(L.quality,s.min))?!0:(D[L.quality]=ot.FitsQualityLimits,!1):(D[L.quality]=ot.FitsThroughput,!1):(D[L.quality]=ot.FitsContainer,!1))[0];q&&q.bitrate&&Js.next(q.bitrate);const U=q??y[Math.ceil((y.length-1)/2)]??a[0];U.quality!==c?.last?.quality&&h({message:`
|
|
6
|
+
var fa="2.0.104";var re=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(re||{}),qe=(b=>(b.MPEG="MPEG",b.DASH="DASH_SEP",b.DASH_SEP="DASH_SEP",b.DASH_SEP_VK="DASH_SEP",b.DASH_WEBM="DASH_WEBM",b.DASH_WEBM_AV1="DASH_WEBM_AV1",b.DASH_WEBM_VK="DASH_WEBM",b.DASH_ONDEMAND="DASH_ONDEMAND",b.DASH_ONDEMAND_VK="DASH_ONDEMAND",b.DASH_LIVE="DASH_LIVE",b.DASH_LIVE_CMAF="DASH_LIVE_CMAF",b.DASH_LIVE_WEBM="DASH_LIVE_WEBM",b.HLS="HLS",b.HLS_ONDEMAND="HLS_ONDEMAND",b.HLS_JS="HLS",b.HLS_LIVE="HLS_LIVE",b.HLS_LIVE_CMAF="HLS_LIVE_CMAF",b.WEB_RTC_LIVE="WEB_RTC_LIVE",b))(qe||{});var wi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(wi||{}),gr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(gr||{});var Sr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Sr||{});import{assertNever as Ta,assertNonNullable as Hn,isNonNullable as $i,ValueSubject as vr,Subject as Qn,Subscription as Gn,merge as Wn,observableFrom as Yn,fromEvent as ga,map as Sa,tap as va,filterChanged as jn,isNullable as yr,ErrorCategory as ya}from"@vkontakte/videoplayer-shared";var ba=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Li=class{constructor(e){this.connection$=new vr(void 0);this.castState$=new vr("NOT_AVAILABLE");this.errorEvent$=new Qn;this.realCastState$=new vr("NOT_AVAILABLE");this.subscription=new Gn;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=$i(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||ba("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ya.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(){$i(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();yr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();yr(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(ga(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 Ta(r.sessionState)}})).add(Wn(ga(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(va(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Sa(r=>r.castState)),Yn([i.getCastState()])).pipe(jn(),Sa(qn),va(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=$i(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Hn(o);let u=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(yr(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?$i(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:ya.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},qn=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 Ta(n)}};import{assertNever as Ia}from"@vkontakte/videoplayer-shared";var Y=(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:Ia(t)}return n},Tr=(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:Ia(e)}};var v=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as zn,Subject as Ri,merge as Ea}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ri;this.transitionEnded$=new Ri;this.transitionUpdated$=new Ri;this.forceChanged$=new Ri;this.stateChangeStarted$=Ea(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ea(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||zn(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 Kn}from"@vkontakte/videoplayer-shared";var xa=n=>{switch(n){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Kn(n)}};import{assertNever as ct,assertNonNullable as ze,debounce as ka,ErrorCategory as Pa,fromEvent as Ke,isNonNullable as Aa,map as wa,merge as $a,observableFrom as Jn,Subject as Xn,Subscription as Ir,timeout as Zn,getHighestQuality as eo}from"@vkontakte/videoplayer-shared";var to=5,io=5,ro=500,La=7e3,kt=class{constructor(e){this.subscription=new Ir;this.loadMediaTimeoutSubscription=new Ir;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(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.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:ct(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:ct(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:ct(e)}break}default:ct(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(xa(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 Ir;this.subscription.add(e),this.subscription.add($a(this.videoState.stateChangeStarted$.pipe(wa(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(wa(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Xn;e.add(r.pipe(ka(ro)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>to)&&r.next(o),a=o})),e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<io&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),v(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:ct(s)}}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=$a(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jn(["init"])).pipe(ka(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"),v(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),v(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"),v(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&v(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,a;switch(e){case"MPEG":{let d=t[e];ze(d);let l=eo(Object.keys(d));ze(l);let c=d[l];ze(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];ze(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let d=t[e];ze(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];ze(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];ze(d),i=Y(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Pa.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return ct(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Aa(o)&&(s.metadata.title=o),Aa(u)&&(s.metadata.subtitle=u),s}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,a)=>{this.loadMediaTimeoutSubscription.add(Zn(La).subscribe(()=>a(`timeout(${La})`)))});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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Pa.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Pt=n=>{n.removeAttribute("src"),n.load()};var Ra=n=>{try{n.pause(),n.playbackRate=0,Pt(n),n.remove()}catch(e){console.error(e)}};var Er=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)}},xr=window.WeakMap?new WeakMap:new Er,q=n=>{let e=n.querySelector("video"),t=!!e;return e?Pt(e):(e=document.createElement("video"),n.appendChild(e)),xr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},z=n=>{let e=xr.get(n);xr.delete(n),e?Pt(n):Ra(n)};import{assertNonNullable as At,isNonNullable as Ie,isNullable as no,fromEvent as pt,merge as Da,observableFrom as Ma,filterChanged as Ca,map as wt,Subject as Ba,Subscription as oo,ValueSubject as uo,ErrorCategory as lo}from"@vkontakte/videoplayer-shared";import{isNonNullable as kr,isNullable as ao,Subscription as so}from"@vkontakte/videoplayer-shared";var Di=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=ao(r),d=new so;return r&&d.add(r.subscribe(l=>{let c=n.getState();i(l,c)&&n.setState(l)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),u&&n.setState(l.to)},a)),d},Te=(n,e,t)=>Di(e,()=>n.loop,i=>{kr(i)&&(n.loop=i)},{onError:t}),K=(n,e,t,i)=>Di(e,()=>({muted:n.muted,volume:n.volume}),r=>{kr(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ne=(n,e,t,i)=>Di(e,()=>n.playbackRate,r=>{kr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Be=Di;var co=n=>["__",n.language,n.label].join("|"),po=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Pr=class n{constructor(){this.available$=new Ba;this.current$=new uo(void 0);this.error$=new Ba;this.subscription=new oo;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:lo.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(Be(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ie(a)&&this.setInternal(a)},{equal:(a,s)=>Ie(a)&&Ie(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(wt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Be(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ie(a)&&this.setExternal(a)},{equal:(a,s)=>Ie(a)&&Ie(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(wt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Be(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Be(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){At(this.video);let{textTracks:e}=this.video;this.subscription.add(pt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Da(pt(e,"addtrack"),pt(e,"removetrack"),Ma(["init"])).pipe(wt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Ca((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Da(pt(e,"change"),Ma(["init"])).pipe(wt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),wt(i=>i&&this.htmlTextTrackToITextTrack(i).id),Ca()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(pt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(pt(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;Ie(t.align)&&(r.align=t.align),Ie(t.position)&&(r.position=t.position),Ie(t.size)&&(r.size=t.size),Ie(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){At(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:co(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,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:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){At(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(no(e)||!po(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){At(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){At(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)}},oe=Pr;var Pe=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 Va=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ar=n=>{let e=Va(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Oa=n=>{let e=Va(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as de,map as Ve,merge as Na,filterChanged as mo,isNonNullable as Fa,Subject as fo,filter as Ua,mapTo as Ha,combine as bo,once as go,ErrorCategory as So,ValueSubject as Qa,getCurrentBrowser as vo,CurrentClientBrowser as yo}from"@vkontakte/videoplayer-shared";var ho=3,_a=(n,e,t=ho)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var J=n=>{let e=P=>de(n,P).pipe(Ha(void 0)),i=Na(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>de(n,P))).pipe(Ve(P=>P.type==="ended"?n.readyState<2:n.readyState<3),mo()),r=Na(de(n,"progress"),de(n,"timeupdate")).pipe(Ve(()=>_a(n.buffered,n.currentTime))),s=vo().browser===yo.Safari?bo({play:e("play").pipe(go()),playing:e("playing")}).pipe(Ha(void 0)):e("playing"),o=de(n,"volumechange").pipe(Ve(()=>({muted:n.muted,volume:n.volume}))),u=de(n,"ratechange").pipe(Ve(()=>n.playbackRate)),d=de(n,"error").pipe(Ua(()=>!!(n.error||n.played.length)),Ve(()=>{let P=n.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:So.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=de(n,"timeupdate").pipe(Ve(()=>n.currentTime)),c=new fo,h=.3,p;l.subscribe(P=>{n.loop&&Fa(p)&&Fa(P)&&p>=n.duration-h&&P<=h&&c.next(p),p=P});let m=de(n,"enterpictureinpicture"),y=de(n,"leavepictureinpicture"),f=new Qa(Oa(n));m.subscribe(()=>f.next(!0)),y.subscribe(()=>f.next(!1));let S=new Qa(Ar(n));return de(n,"fullscreenchange").pipe(Ve(()=>Ar(n))).subscribe(S),{playing$:s,pause$:e("pause").pipe(Ua(()=>!n.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:de(n,"durationchange").pipe(Ve(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:f,inFullscreen$:S}};import{VideoQuality as Oe}from"@vkontakte/videoplayer-shared";var _e=n=>{switch(n){case"mobile":return Oe.Q_144P;case"lowest":return Oe.Q_240P;case"low":return Oe.Q_360P;case"sd":case"medium":return Oe.Q_480P;case"hd":case"high":return Oe.Q_720P;case"fullhd":case"full":return Oe.Q_1080P;case"quadhd":case"quad":return Oe.Q_1440P;case"ultrahd":case"ultra":return Oe.Q_2160P}};import{isNonNullable as Ne,isNullable as $r,now as za,isHigher as Lr,isHigherOrEqual as ja,isInvariantQuality as qa,isLower as Rr,isLowerOrEqual as To,videoSizeToQuality as Io,assertNotEmptyArray as Eo}from"@vkontakte/videoplayer-shared";var wr=!1,Ae={},Ga=n=>{wr=n},Wa=()=>{Ae={}},Ya=n=>{n(Ae)},$t=(n,e)=>{wr&&(Ae.meta=Ae.meta??{},Ae.meta[n]=e)},j=class{constructor(e){this.name=e}next(e){if(!wr)return;Ae.series=Ae.series??{};let t=Ae.series[this.name]??[];t.push([Date.now(),e]),Ae.series[this.name]=t}};var xo=new j("best_bitrate"),ko=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,Mi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=za()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Po='Assertion "ABR Tracks is empty array" failed',Ao=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{Eo(n,Po);let h=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*i.containerSizeFactor,height:e.height*h*i.containerSizeFactor},m=p&&Io(p),y=i.considerPlaybackRate&&Ne(o)?o:1,f=n.filter(I=>!qa(I.quality)).sort((I,E)=>Lr(I.quality,E.quality)?-1:1),S=f.at(-1)?.quality,b=f.at(0)?.quality,P=$r(r)||Ne(r.min)&&Ne(r.max)&&Rr(r.max,r.min)||Ne(r.min)&&b&&Lr(r.min,b)||Ne(r.max)&&S&&Rr(r.max,S),g=y*ko(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),T={},L=f.filter(I=>(m?Rr(I.quality,m):!0)?(Ne(t)&&isFinite(t)&&Ne(I.bitrate)?t-a>=I.bitrate*g:!0)?i.lazyQualitySwitch&&Ne(i.minBufferToSwitchUp)&&u&&!qa(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Lr(I.quality,u.quality)?(T[I.quality]="Buffer",!1):!!l&&ja(I.quality,l)?(T[I.quality]="DroppedFramesLimit",!1):P||($r(r.max)||To(I.quality,r.max))&&($r(r.min)||ja(I.quality,r.min))?!0:(T[I.quality]="FitsQualityLimits",!1):(T[I.quality]="FitsThroughput",!1):(T[I.quality]="FitsContainer",!1))[0];L&&L.bitrate&&xo.next(L.bitrate);let A=L??f[Math.ceil((f.length-1)/2)]??n[0];A.quality!==d?.last?.quality&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${
|
|
8
|
+
${n.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(i??{}).map(([
|
|
12
|
+
${Object.entries(i??{}).map(([I,E])=>`${I}: ${E}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${m},
|
|
17
17
|
throughput: ${t},
|
|
18
|
-
reserve: ${
|
|
18
|
+
reserve: ${a},
|
|
19
19
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
21
|
-
forwardBufferHealth: ${
|
|
22
|
-
bitrateFactor: ${
|
|
20
|
+
playbackRateFactor: ${y},
|
|
21
|
+
forwardBufferHealth: ${s},
|
|
22
|
+
bitrateFactor: ${g},
|
|
23
23
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
25
|
-
limitsAreInvalid: ${
|
|
26
|
-
maxQualityLimit: ${
|
|
27
|
-
minQualityLimit: ${
|
|
24
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
25
|
+
limitsAreInvalid: ${P},
|
|
26
|
+
maxQualityLimit: ${r?.max},
|
|
27
|
+
minQualityLimit: ${r?.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(T).map(([I,E])=>`${I}: ${E}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),L}return c?.recordSwitch(U),U};var qe=a=>new URL(a).hostname,H;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(H||(H={}));const _i=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var gt=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!_i(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return _i(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function be(){return ae()}function as(a){return be()-a}function Oi(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,s=n=>i.test(n);return{resolve:(n,o,d=!1)=>{s(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return d&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ea(a,e,t){const i=(...s)=>{t.apply(null,s),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Jt(a,e,t,i){const s=window.XMLHttpRequest;let r,n,o,d=!1,c=0,u,h,p=!1,f="arraybuffer",S=7e3,w=2e3,y=()=>{if(d)return;v(u);const Y=as(u);let ce;if(Y<w){ce=w-Y,setTimeout(y,ce);return}w*=2,w>S&&(w=S),n&&n.abort(),n=new s,J()};const $=Y=>(r=Y,I),_=Y=>(h=Y,I),M=()=>(f="json",I),E=()=>{if(!d){if(--c>=0){y(),i&&i();return}d=!0,h&&h(),t&&t()}},D=Y=>(p=Y,I),J=()=>{u=be(),n=new s,n.open("get",a);let Y=0,ce,fe=0;const Re=()=>(v(u),Math.max(u,Math.max(ce||0,fe||0)));if(r&&n.addEventListener("progress",B=>{const j=be();r.updateChunk&&B.loaded>Y&&(r.updateChunk(Re(),B.loaded-Y),Y=B.loaded,ce=j)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(d)return;v(n);const B=n.status;if(B>=200&&B<300){if(n.response.byteLength&&r){const j=n.response.byteLength-Y;j&&r.updateChunk&&r.updateChunk(Re(),j)}n.responseType==="json"&&!Object.values(n.response).length?E():(h&&h(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){const B=()=>{v(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(fe=be(),n.removeEventListener("readystatechange",B))};n.addEventListener("readystatechange",B)}return n.responseType=f,n.send(),I},I={withBitrateReporting:$,withParallel:D,withJSONResponse:M,withRetryCount:Y=>(c=Y,I),withRetryInterval:(Y,ce)=>(A(Y)&&(w=Y),A(ce)&&(S=ce),I),withTimeout:Y=>(o=Y,I),withFinally:_,send:J,abort:()=>{n&&(n.abort(),n=void 0),d=!0,h&&h()}};return I}const ta=100,ia=2e3,sa=500;let aa=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-sa;if(t-e>ia){let i=0,s=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)i+=r.end-r.start,s+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;i+=n;const d=r.bytes*n/o;s+=d,r.start=t,r.bytes-=d}}}if(s>0&&i>0){const r=s*8/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>ta&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class ra{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,s,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=be(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},r=d=>{e._complete=1,e._responseData=d,e._downloadTime=be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Jt(t,r,()=>s("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=be()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=be();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,s){const r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=s,n._finallyCB=r._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),r._finallyCB&&r._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(r,e)}},r._cb=t,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=n=>(r._finallyCB=n,r),r}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Wt=1e4,fi=3,na=6e4,oa=10,ca=1,da=500;class ua{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new aa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Oi(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Oi(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let s;i!==0&&(s=t.buffered.start(i-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let i,s,r;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)r=this.manifest[o],!(this.maxAutoQuality&&r.video.height>this.maxAutoQuality)&&(r.bitrate<e&&n>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||A(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{ea(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ra(fi,Wt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:s}=this.params;let r=!1,n=null,o=null,d=null,c=null,u=!1;const h=()=>{const E=r&&(!u||u===this.rep);return E||t("Not running!"),E},p=(E,D,J)=>{d&&d.abort(),d=Jt(this.urlResolver.resolve(E,!1),D,J,()=>this._retryCallback()).withTimeout(Wt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fi).withFinally(()=>{d=null}).send()},f=(E,D,J)=>{v(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),D,J,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=E=>{const D=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${D}=>${E}`),i.playbackRate=E)},w=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)S(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const J=be()-1e4;let q=0;for(let W=0;W<this.bufferStates.length;W++){const L=this.bufferStates[W];E=Math.min(E,L.buf),L.ts<J&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${E} drop=${q} jitter=${this.sourceJitter}`);let U=E-ca;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?S(1.15):U>1?S(1.1):U>.3?S(1.05):S(1)}},$=E=>{let D;const J=()=>D&&D.start?D.start.length:0,q=B=>D.start[B]/1e3,U=B=>D.dur[B]/1e3,W=B=>D.fragIndex+B,L=(B,j)=>({chunkIdx:W(B),startTS:q(B),dur:U(B),discontinuity:j}),I=()=>{let B=0;if(D&&D.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=j;this.sourceJitter>1&&(he+=this.sourceJitter-1);let ve=D.dur.length-1;for(;ve>=0&&(he-=D.dur[ve],!(he<=0));--ve);B=Math.min(ve,D.dur.length-1-ue),B=Math.max(B,0)}return L(B,!0)},Y=B=>{const j=J();if(!(j<=0)){if(A(B)){for(let ue=0;ue<j;ue++)if(q(ue)>B)return L(ue)}return I()}},ce=B=>{const j=J(),ue=B?B.chunkIdx+1:0,he=ue-D.fragIndex;if(!(j<=0)){if(!B||he<0||he-j>oa)return t(`Resync: offset=${he} bChunks=${j} chunk=`+JSON.stringify(B)),I();if(!(he>=j))return L(ue-D.fragIndex,!1)}},fe=(B,j,ue)=>{c&&c.abort(),c=Jt(this.urlResolver.resolve(B,!0,this.lowLatency),j,ue,()=>this._retryCallback()).withTimeout(Wt).withRetryCount(fi).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(B,j)=>{fe(E,ue=>{if(!h())return;D=ue;const he=!!D.lowLatency;he!==this.lowLatency&&w(he);let ve=0;for(let Xe=0;Xe<D.dur.length;++Xe)ve+=D.dur[Xe];ve>0&&(v(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/D.dur.length)),s({name:"index",zeroTime:D.zeroTime,shiftDuration:D.shiftDuration}),this.sourceJitter=D.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,D.jitter/1e3)):1,B(Y(j))},()=>this._handleNetworkError())},nextChunk:ce}},_=()=>{r=!1,o&&o.abort(),d&&d.abort(),c&&c.abort(),v(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:E=>{const{videoElement:D,logger:J}=this.params;let q=$(e.jidxUrl),U,W,L,I,Y=0,ce,fe,Re;const B=()=>{ce&&(clearTimeout(ce),ce=void 0);const X=Math.max(da,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=Y+X,Ae=be(),Ie=Math.min(1e4,Ee-Ae);Y=Ae;const ze=()=>{c||h()&&q.seek(()=>{h()&&(Y=be(),j(),B())})};Ie>0?ce=window.setTimeout(()=>{this.paused?B():ze()},Ie):ze()},j=()=>{let X;for(;X=q.nextChunk(I);)I=X,ni(X);const Ee=q.nextChunk(L);if(Ee){if(L&&Ee.discontinuity){J("Detected discontinuity; restarting playback"),this.paused?B():(_(),this._initPlayerWith(e));return}Xe(Ee)}else B()},ue=(X,Ee)=>{if(!h()||!this.sourceBuffer)return;let Ae,Ie,ze;const Lt=$e=>{window.setTimeout(()=>{h()&&ue(X,Ee)},$e)};if(this.sourceBuffer.updating)J("Source buffer is updating; delaying appendBuffer"),Lt(100);else{const $e=be(),Ke=D.currentTime;!this.paused&&D.buffered.length>1&&fe===Ke&&$e-Re>500&&(J("Stall suspected; trying to fix"),this._fixupStall()),fe!==Ke&&(fe=Ke,Re=$e);const Be=this._getBufferSizeSec();if(Be>30)J(`Buffered ${Be} seconds; delaying appendBuffer`),Lt(2e3);else try{this.sourceBuffer.appendBuffer(X),this.videoPlayStarted?(this.bufferStates.push({ts:$e,buf:Be}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ne){if(Ne.name==="QuotaExceededError")J("QuotaExceededError; delaying appendBuffer"),ze=this.sourceBuffer.buffered.length,ze!==0&&(Ae=this.sourceBuffer.buffered.start(0),Ie=Ke,Ie-Ae>4&&this.sourceBuffer.remove(Ae,Ie-3)),Lt(1e3);else throw Ne}}},he=()=>{W&&U&&(J([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(L)]),ue(W,function(){W=null,j()}))},ve=X=>e.fragUrlTemplate.replace("%%id%%",X.chunkIdx),Xe=X=>{h()&&f(ve(X),(Ee,Ae)=>{if(h()){if(Ae/=1e3,W=Ee,L=X,n=X.startTS,Ae){const Ie=Math.min(10,X.dur/Ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}he()}},()=>this._handleNetworkError())},ni=X=>{h()&&(v(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(X),!1)))},Ut=X=>{h()&&(e.cachedHeader=X,ue(X,()=>{U=!0,he()}))};r=!0,q.seek(X=>{if(h()){if(Y=be(),!X){B();return}I=X,!Q(E)||X.startTS>E?Xe(X):(L=X,j())}},E),e.cachedHeader?Ut(e.cachedHeader):p(e.headerUrl,Ut,()=>this._handleNetworkError())},stop:_,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),A(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,v(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return A(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let p,f,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(f=this._getBufferSizeSec(),S=h/this.bitrate,f>10&&S>.8||f>15&&S>.5||f>20&&S>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}p=this._selectQuality(h),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${h}`)},r=(()=>({updateChunk:(p,f)=>{const S=be();if(this.chunkRateEstimator.addInterval(p,S,f)){const y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:S-p,speed:y}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let n=-1/0,o,d=!0;const c=()=>{let h=r.get();if(h&&o&&this.autoQuality){if(d&&h>o&&as(n)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,p)=>{const f=r.updateChunk(h,p);return f&&c(),f},notifySwitch:h=>{const p=be();h<o&&(n=p),o=h}}}_fetchManifest(e,t,i){this.manifestRequest=Jt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Wt).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){const{videoElement:e}=this.params;gt(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(H.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:s}=this.params,r=n=>{const o=[];return n?.length?(n.forEach((d,c)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=c,o.push(d))}),o.sort(function(d,c){return d.video&&c.video?c.video.height-d.video.height:c.bitrate-d.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=r(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},na))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class rs{onDroopedVideoFramesLimit$=new x;subscription=new ee;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new x;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Bt(this.droppedFramesChecker.checkTime).pipe(oe(()=>this.playing),oe(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(Ge(this.droppedFramesChecker.checkTime)),i=O(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!ut(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,s=t-this.prevDroppedVideoFrames,r=1-(i-s)/i;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&$t(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[s])=>Qt(i,s)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const yi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,Dt=(a,e)=>new ki(t=>{if(!window.IntersectionObserver)return;const i={root:null},s=new IntersectionObserver((n,o)=>{n.forEach(d=>t.next(d.isIntersecting||yi()))},{...i,...e});s.observe(a);const r=C(document,"visibilitychange").pipe(T(n=>!document.hidden||yi())).subscribe(n=>t.next(n));return()=>{s.unobserve(a),r.unsubscribe}}),ha=[H.PAUSED,H.PLAYING,H.READY],la=[H.PAUSED,H.PLAYING,H.READY];class fa{subscription=new ee;video;videoState=new ne(H.STOPPED);dash;representations$=new g([]);textTracksManager=new it;droppedFramesManager=new rs;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new Pi;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:P.WTF,message:"DashLiveProvider internal logic error",thrown:s})};O(this.videoState.stateChangeStarted$.pipe(T(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(T(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(s)}`})}),this.video=lt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=mt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(T(s=>s.map(({track:r})=>r)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===G.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(H.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(de(),T(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(Le({zeroTime:this.zeroTime$.pipe(oe(A)),position:i.timeUpdate$}).subscribe(({zeroTime:s,position:r})=>this.params.output.liveTime$.next(s+r*1e3),t)).add(Vt(this.video,this.params.desiredState.isLooped,t)).add(pt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Dt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const r=s&&$s(s);this.dash.setMaxAutoQuality(r),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case H.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case H.MANIFEST_READY:case H.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case H.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case H.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return V(s.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ft(this.video)}createLiveDashPlayer(){const e=new ua({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),s=!i&&A(t)?t:ri(e.map(({track:c})=>c),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),r=s?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&(n||r!==o)&&this.setVideoTrack(s),d&&this.setAutoQuality(i),n||d||r!==o){const c=e.find(({track:u})=>u.id===r)?.representation;v(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;v(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===H.PAUSED,r=-e,n=r<=this.maxSeekBackTime$.getValue()?r:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Oe(this.params.source.url,n)),s&&this.dash.pause(),this.liveOffset.resetTo(n,s)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:P.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const s of t){const r=s.name??s.index.toString(10),n=ai(s.name)??dt(s.video),o=s.bitrate/1e3,d={...s.video};if(!n)continue;const c={id:r,quality:n,bitrate:o,size:d};i.push({track:c,representation:s})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:s})=>s)),this.videoState.getTransition()?.to===H.MANIFEST_READY&&this.videoState.setState(H.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:s})=>s===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),A(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i===l.STOPPED){e!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(H.STOPPED));return}if(t)return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(la.includes(e)&&(n||o)){this.prepare();return}if(s?.to!==l.PAUSED&&r.state===G.Requested&&ha.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case H.STOPPED:this.videoState.startTransitionTo(H.MANIFEST_READY),this.dash.attachSource(Oe(this.params.source.url));return;case H.MANIFEST_READY:this.videoState.startTransitionTo(H.READY),this.prepare();break;case H.READY:if(i===l.PAUSED)this.videoState.setState(H.PAUSED);else if(i===l.PLAYING){this.videoState.startTransitionTo(H.PLAYING);const d=s?.from;d&&d===l.READY&&this.dash.catchUp(),this.dash.play()}return;case H.PLAYING:i===l.PAUSED&&(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case H.PAUSED:if(i===l.PLAYING)if(this.videoState.startTransitionTo(H.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(Oe(this.params.source.url,d))}return;default:return V(e)}}}var me;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(me||(me={}));var Ve;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(Ve||(Ve={}));var Zt;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Zt||(Zt={}));var xe;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(xe||(xe={}));var N;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(N||(N={}));var kt;(function(a){a.MP4="mp4",a.WEBM="webm"})(kt||(kt={}));var ei;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(ei||(ei={}));var se;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(se||(se={}));var Mt=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const s=a.start(i)*1e3,r=a.end(i)*1e3;s<=e&&e<=r&&(t=r)}return Math.max(t-e,0)},Ti=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const pa=16;let ns=!1;try{ns=$i().browser===is.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=pa}catch(a){console.error(a)}class ma{bufferFull$=new x;error$=new x;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const r={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let i;ns&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:P.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:P.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:V(t)}}}var Ni=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class we{source;boxParser;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];const i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;const s=this.size32?this.size32-8:void 0,r=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,r,s),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class os extends we{}class ga extends we{}class Sa extends we{majorBrand;minorVersion;compatibleBrands;constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){const s=this.readString(4);this.compatibleBrands.push(s),i-=4}}}class ba extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ya extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ta extends we{data;constructor(e,t){super(e,t),this.data=this.content}}class Je extends we{version;flags;constructor(e,t){super(e,t);const i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}}class cs extends Je{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const d=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:d,SAPDeltaTime:c})}}}class va extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ea extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var ct;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(ct||(ct={}));class Aa extends Je{stereoMode;constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=ct.MONOSCOPIC;break;case 1:this.stereoMode=ct.TOP_BOTTOM;break;case 2:this.stereoMode=ct.LEFT_RIGHT;break;case 3:this.stereoMode=ct.STEREO_CUSTOM;break;case 4:this.stereoMode=ct.RIGHT_LEFT;break}this.cursor+=1}}class $a extends Je{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class ka extends Je{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class wa extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Pa extends Je{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Da extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class La extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class xa extends Je{sequenceNumber;constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class Ca extends we{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ra extends Je{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Ia extends Je{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Ba extends Je{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}var ie;(function(a){a.FtypBox="ftyp",a.MoovBox="moov",a.MoofBox="moof",a.MdatBox="mdat",a.SidxBox="sidx",a.TrakBox="trak",a.MdiaBox="mdia",a.MfhdBox="mfhd",a.TkhdBox="tkhd",a.TrafBox="traf",a.TfhdBox="tfhd",a.TfdtBox="tfdt",a.TrunBox="trun",a.MinfBox="minf",a.Sv3dBox="sv3d",a.St3dBox="st3d",a.PrhdBox="prhd",a.ProjBox="proj",a.EquiBox="equi",a.UuidBox="uuid",a.UnknownBox="unknown"})(ie||(ie={}));const Ma={[ie.FtypBox]:Sa,[ie.MoovBox]:ba,[ie.MoofBox]:ya,[ie.MdatBox]:Ta,[ie.SidxBox]:cs,[ie.TrakBox]:va,[ie.MdiaBox]:wa,[ie.MfhdBox]:xa,[ie.TkhdBox]:Pa,[ie.TrafBox]:Ca,[ie.TfhdBox]:Ra,[ie.TfdtBox]:Ia,[ie.TrunBox]:Ba,[ie.MinfBox]:Da,[ie.Sv3dBox]:Ea,[ie.St3dBox]:Aa,[ie.PrhdBox]:$a,[ie.ProjBox]:La,[ie.EquiBox]:ka,[ie.UuidBox]:ga,[ie.UnknownBox]:os};class ht{options;constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let i=this.options.offset;for(;i<e.byteLength;)try{const r=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(r,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){const i=Ma[e];return i?new i(t,new ht):new os(t,new ht)}}class Li{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const _a=new TextDecoder("ascii"),Oa=a=>_a.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Na=a=>{const e=new cs(a,new ht);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(r=>{if(r.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=r.subsegmentDuration/e.timescale*1e3,o={status:N.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+r.referencedSize-1}};return t+=n,i+=r.referencedSize,o})},Fa=(a,e)=>{const i=new ht().parse(a),s=new Li(i),r=s.findAll("moof"),n=e?s.findAll("uuid"):s.findAll("mdat");if(!(n.length&&r.length))return null;const o=r[0],d=n[n.length-1],c=o.source.byteOffset,h=d.source.byteOffset-o.source.byteOffset+d.size;return new DataView(a.buffer,c,h)},Va=(a,e)=>{const i=new ht().parse(a),r=new Li(i).findAll("traf"),n=r[r.length-1].children.find(h=>h.type==="tfhd"),o=r[r.length-1].children.find(h=>h.type==="tfdt"),d=r[r.length-1].children.find(h=>h.type==="trun");let c=0;return d.sampleDuration.length?c=d.sampleDuration.reduce((h,p)=>h+p,0):c=n.defaultSampleDuration*d.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},Ua=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ei.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ht().parse(a),s=new Li(i);if(s.find("sv3d")){e.is3dVideo=!0;const n=s.find("st3d");n&&(e.stereoMode=n.stereoMode);const o=s.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);const d=s.find("equi");d&&(e.projectionData.bounds.top=d.projectionBoundsTop,e.projectionData.bounds.right=d.projectionBoundsRight,e.projectionData.bounds.bottom=d.projectionBoundsBottom,e.projectionData.bounds.left=d.projectionBoundsLeft)}return e},Ha={validateData:Oa,parseInit:Ua,getIndexRange:()=>{},parseSegments:Na,parseFeedableSegmentChunk:Fa,getSegmentEndTime:Va};var b;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(b||(b={}));var k;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(k||(k={}));const Fi={[b.EBML]:{type:k.Master},[b.EBMLVersion]:{type:k.UnsignedInteger},[b.EBMLReadVersion]:{type:k.UnsignedInteger},[b.EBMLMaxIDLength]:{type:k.UnsignedInteger},[b.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[b.DocType]:{type:k.String},[b.DocTypeVersion]:{type:k.UnsignedInteger},[b.DocTypeReadVersion]:{type:k.UnsignedInteger},[b.Void]:{type:k.Binary},[b.Segment]:{type:k.Master},[b.SeekHead]:{type:k.Master},[b.Seek]:{type:k.Master},[b.SeekID]:{type:k.Binary},[b.SeekPosition]:{type:k.UnsignedInteger},[b.Info]:{type:k.Master},[b.TimestampScale]:{type:k.UnsignedInteger},[b.Duration]:{type:k.Float},[b.Tracks]:{type:k.Master},[b.TrackEntry]:{type:k.Master},[b.Video]:{type:k.Master},[b.Projection]:{type:k.Master},[b.ProjectionType]:{type:k.UnsignedInteger},[b.ProjectionPrivate]:{type:k.Master},[b.Chapters]:{type:k.Master},[b.Cluster]:{type:k.Master},[b.Timestamp]:{type:k.UnsignedInteger},[b.SilentTracks]:{type:k.Master},[b.SilentTrackNumber]:{type:k.UnsignedInteger},[b.Position]:{type:k.UnsignedInteger},[b.PrevSize]:{type:k.UnsignedInteger},[b.SimpleBlock]:{type:k.Binary},[b.BlockGroup]:{type:k.Master},[b.EncryptedBlock]:{type:k.Binary},[b.Attachments]:{type:k.Master},[b.Tags]:{type:k.Master},[b.Cues]:{type:k.Master},[b.CuePoint]:{type:k.Master},[b.CueTime]:{type:k.UnsignedInteger},[b.CueTrackPositions]:{type:k.Master},[b.CueTrack]:{type:k.UnsignedInteger},[b.CueClusterPosition]:{type:k.UnsignedInteger},[b.CueRelativePosition]:{type:k.UnsignedInteger},[b.CueDuration]:{type:k.UnsignedInteger},[b.CueBlockNumber]:{type:k.UnsignedInteger},[b.CueCodecState]:{type:k.UnsignedInteger},[b.CueReference]:{type:k.Master},[b.CueRefTime]:{type:k.UnsignedInteger}},ds=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ti(a,t),s=i in Fi,r=s?Fi[i].type:k.Binary,n=a.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const d=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,u=ti(d),h=c*2**((o-1)*8)+u,p=t+o;let f;return p+h>a.byteLength?f=new DataView(a.buffer,a.byteOffset+p):f=new DataView(a.buffer,a.byteOffset+p,h),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:r,tagHeaderSize:p,tagSize:p+h,value:f,valueSize:h}},ti=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(a,e)=>{switch(e){case k.SignedInteger:return a.getInt8(0);case k.UnsignedInteger:return ti(a);case k.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(a);case k.UTF8:return new TextDecoder("utf-8").decode(a);case k.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case k.Master:return a;case k.Binary:return a;default:V(e)}},wt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=ds(i);if(!e(s))return;s.type===k.Master&&wt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},Ya=a=>{if(a.getUint32(0)!==b.EBML)return!1;let e,t,i;const s=ds(a);return wt(s.value,({tag:r,type:n,value:o})=>(r===b.EBMLReadVersion?e=He(o,n):r===b.DocType?t=He(o,n):r===b.DocTypeReadVersion&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},us=[b.Info,b.SeekHead,b.Tracks,b.TrackEntry,b.Video,b.Projection,b.ProjectionType,b.ProjectionPrivate,b.Chapters,b.Cluster,b.Cues,b.Attachments,b.Tags],Ga=[b.Timestamp,b.SilentTracks,b.SilentTrackNumber,b.Position,b.PrevSize,b.SimpleBlock,b.BlockGroup,b.EncryptedBlock],qa=a=>{let e,t,i,s,r=!1,n=!1,o=!1,d,c,u=!1;const h=0;return wt(a,({tag:p,type:f,value:S,valueSize:w})=>{if(p===b.SeekID){const y=He(S,f);c=ti(y)}else p!==b.SeekPosition&&(c=void 0);return p===b.Segment?(e=S.byteOffset,t=S.byteOffset+w):p===b.Info?r=!0:p===b.SeekHead?n=!0:p===b.TimestampScale?i=He(S,f):p===b.Duration?s=He(S,f):p===b.SeekPosition&&c===b.Cues?d=He(S,f):p===b.Tracks?wt(S,({tag:y,type:$,value:_})=>y===b.ProjectionType?(u=He(_,$)===1,!1):!0):r&&n&&us.includes(p)&&(o=!0),!o}),v(e,"Failed to parse webm Segment start"),v(t,"Failed to parse webm Segment end"),v(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:u,stereoMode:h,projectionType:ei.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},za=a=>{if(Q(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wa=(a,e)=>{let t=!1,i=!1;const s=o=>A(o.time)&&A(o.position),r=[];let n;return wt(a,({tag:o,type:d,value:c})=>{switch(o){case b.Cues:t=!0;break;case b.CuePoint:n&&s(n)&&r.push(n),n={};break;case b.CueTime:n&&(n.time=He(c,d));break;case b.CueTrackPositions:break;case b.CueClusterPosition:n&&(n.position=He(c,d));break;default:t&&us.includes(o)&&(i=!0)}return!(t&&i)}),n&&s(n)&&r.push(n),r.map((o,d)=>{const{time:c,position:u}=o,h=r[d+1];return{status:N.NONE,time:{from:c,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},Qa=a=>{let e=0,t=!1;try{wt(a,i=>i.tag===b.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ga.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[b.SimpleBlock,b.BlockGroup,b.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},ja={validateData:Ya,parseInit:qa,getIndexRange:za,parseSegments:Wa,parseFeedableSegmentChunk:Qa},Ja=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)},Vi=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const d=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(d)?0:d)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),s=i?.[1]==="-"?-1:1,r={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},vt=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,r]of Object.entries(i)){const n=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,d)=>Q(r)?o:Q(d)?r:r.padStart(parseInt(d,10),"0"))}return t},Xa=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},r=i.children[0],n=r.getElementsByTagName("Period")[0],o=r.querySelector("BaseURL")?.textContent?.trim()??"",d=n.children,c=r.getAttribute("type")==="dynamic",u=r.getAttribute("availabilityStartTime"),h=u?new Date(u).getTime():void 0;let p;const f=r.getAttribute("mediaPresentationDuration"),S=n.getAttribute("duration"),y=r.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Vi(f);else if(S){const E=Vi(S);A(E)&&(p=E)}else y&&(p=parseInt(y,10));let $=0;const _=r.getAttribute("profiles")?.split(",")??[],M=_.includes(Zt.WEBM_AS_IN_FFMPEG)||_.includes(Zt.WEBM_AS_IN_SPEC)?kt.WEBM:kt.MP4;for(const E of d){const D=E.getAttribute("mimeType"),J=E.getAttribute("codecs"),q=E.getAttribute("contentType")??D?.split("/")[0],U=E.getAttribute("profiles")?.split(",")??[],W=E.querySelectorAll("Representation"),L=E.querySelector("SegmentTemplate");if(q===me.TEXT){for(const I of W){const Y=I.getAttribute("id")||"",ce=E.getAttribute("lang"),fe=E.getAttribute("label"),Re=I.querySelector("BaseURL")?.textContent?.trim()??"",B=new URL(Re||o,e).toString(),j=Y.includes("_auto");s[me.TEXT].push({id:Y,lang:ce,label:fe,isAuto:j,kind:me.TEXT,url:B})}continue}for(const I of W){const Y=I.getAttribute("mimeType")??D,ce=I.getAttribute("codecs")??J??"",fe=I.getAttribute("contentType")??Y?.split("/")[0]??q,Re=E.getAttribute("profiles")?.split(",")??[],B=parseInt(I.getAttribute("width")??"",10),j=parseInt(I.getAttribute("height")??"",10),ue=parseInt(I.getAttribute("bandwidth")??"",10)/1e3,he=I.getAttribute("frameRate")??"",ve=I.getAttribute("quality")??void 0,Xe=he?Ja(he):void 0,ni=I.getAttribute("id")??($++).toString(10),Ut=fe==="video"?`${j}p`:fe==="audio"?`${ue}Kbps`:ce,X=`${ni}@${Ut}`,Ee=I.querySelector("BaseURL")?.textContent?.trim()??"",Ae=new URL(Ee||o,e).toString(),Ie=[..._,...U,...Re];let ze;const Lt=I.querySelector("SegmentBase"),$e=I.querySelector("SegmentTemplate")??L;if(Lt){const Be=I.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,oi]=Be.split("-").map(St=>parseInt(St,10)),Ze={from:Ne,to:oi},xt=I.querySelector("SegmentBase")?.getAttribute("indexRange"),[ci,Ht]=xt?xt.split("-").map(St=>parseInt(St,10)):[],Ct=xt?{from:ci,to:Ht}:void 0;ze={type:xe.BYTE_RANGE,url:Ae,initRange:Ze,indexRange:Ct}}else if($e){const Be={representationId:I.getAttribute("id")??void 0,bandwidth:I.getAttribute("bandwidth")??void 0},Ne=parseInt($e.getAttribute("timescale")??"",10),oi=$e.getAttribute("initialization")??"",Ze=$e.getAttribute("media"),xt=parseInt($e.getAttribute("startNumber")??"",10)??1,ci=vt(oi,Be);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Ht=$e.querySelectorAll("SegmentTimeline S")??[],Ct=[];let St=0,di="",ui=0;if(Ht.length){let Yt=xt,Me=0;for(const bt of Ht){const Fe=parseInt(bt.getAttribute("d")??"",10),st=parseInt(bt.getAttribute("r")??"",10)||0,Gt=parseInt(bt.getAttribute("t")??"",10);Me=Number.isFinite(Gt)?Gt:Me;const hi=Fe/Ne*1e3,bs=Me/Ne*1e3;for(let qt=0;qt<st+1;qt++){const ys=vt(Ze,{...Be,segmentNumber:Yt.toString(10),segmentTime:(Me+qt*Fe).toString(10)}),Ri=(bs??0)+qt*hi,Ts=Ri+hi;Yt++,Ct.push({time:{from:Ri,to:Ts},url:ys})}Me+=(st+1)*Fe,St+=(st+1)*hi}ui=Me/Ne*1e3,di=vt(Ze,{...Be,segmentNumber:Yt.toString(10),segmentTime:Me.toString(10)})}else if(A(p)){const Me=parseInt($e.getAttribute("duration")??"",10)/Ne*1e3,bt=Math.ceil(p/Me);let Fe=0;for(let st=1;st<bt;st++){const Gt=vt(Ze,{...Be,segmentNumber:st.toString(10),segmentTime:Fe.toString(10)});Ct.push({time:{from:Fe,to:Fe+Me},url:Gt}),Fe+=Me}ui=Fe,di=vt(Ze,{...Be,segmentNumber:bt.toString(10),segmentTime:Fe.toString(10)})}const Ss={time:{from:ui,to:1/0},url:di};ze={type:xe.TEMPLATE,baseUrl:Ae,segmentTemplateUrl:Ze,initUrl:ci,totalSegmentsDurationMs:St,segments:Ct,nextSegmentBeyondManifest:Ss,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!fe||!Y)continue;const Ke={video:me.VIDEO,audio:me.AUDIO,text:me.TEXT}[fe];Ke&&s[Ke].push({id:X,kind:Ke,segmentReference:ze,profiles:Ie,duration:p,bitrate:ue,mime:Y,codecs:ce,width:B,height:j,fps:Xe,quality:ve})}}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,container:M,representations:s}},Ka=({id:a,width:e,height:t,bitrate:i,fps:s,quality:r})=>{const n=(r?ai(r):void 0)??dt({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:s}},Za=({id:a,bitrate:e})=>({id:a,bitrate:e}),er=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},tr=({id:a,lang:e,label:t,url:i,isAuto:s})=>({id:a,url:i,isAuto:s,type:"internal",language:e,label:t}),Ui=a=>"url"in a,yt=a=>a.type===xe.TEMPLATE,vi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class Hi{currentSegmentLength$=new g(0);onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new x;gaps=[];subscription=new ee;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;loadByteRangeSegmentsTimeoutId=0;constructor(e,t,i,s,{fetcher:r,tuning:n,getCurrentPosition:o,isActiveLowLatency:d,compatibilityMode:c=!1,manifest:u}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=d,this.isLive=!!u?.dynamic,this.container=i,i){case kt.MP4:this.containerParser=Ha;break;case kt.WEBM:this.containerParser=ja;break;default:V(i)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=Te(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);v(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ma(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:P.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,Ni(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),r=this.parsedInitData.get(t.id);v(i,"No init buffer for starting representation"),v(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(r))}.bind(this));switchTo=Te(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);v(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Q(s)||Q(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),v(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const r=this.getCurrentPosition();A(r)&&(this.isLive||(i.forEach(n=>n.status=N.NONE),this.pruneBuffer(r,1/0,!0)),this.maintain(r))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(v(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next((s?.time.to??0)-(s?.time.from??0));let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=Mt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&u>=s.time.to-e+100&&(r=h)}if(isFinite(this.bufferLimit)&&Ni(this.sourceBuffer.buffered)>=this.bufferLimit){const c=Mt(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,r),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(o.includes(s))c="high";else{const u=o.at(0);u&&u.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===N.FED&&!o.length&&Mt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=i.at(-1);d&&d.status===N.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const r of e)Math.trunc(r.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from+s}),i=r.time.to;A(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let r=0,n=t.length-1;do s.unshift(t[n]),r+=t[n].time.to-t[n].time.from,n--;while(r<i&&n>=0);return this.liveInitialAdditionalOffset=r-i,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=Te(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const o of this.representations.keys()){const d=e.find(h=>h.id===o);d&&this.representations.set(o,d);const c=this.representations.get(o);if(!c||!yt(c.segmentReference))return;const u=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,u)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);v(i);const s=this.segments.get(t);v(s,"No segments for starting representation");const r=this.initData.get(t);if(v(r,"No init buffer for starting representation"),!(r instanceof ArrayBuffer))return;const n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!yt(t.segmentReference))return;const i=t.segmentReference.segments.map(o=>({...o,status:N.NONE,size:void 0})),s=this.segments.get(t.id)??[],r=s.at(-1)?.time.to??0,n=i?.findIndex(o=>Math.floor(r)>=Math.floor(o.time.from)&&Math.floor(r)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;const o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{const o=i.slice(n+1);this.segments.set(t.id,[...s,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!yt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),r=vt(i.segmentTemplateUrl,{segmentTime:s}),n=this.segments.get(t.id)??[],o=n.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||n.push({status:N.NONE,time:{from:e.segment.time.to,to:1/0},url:r})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(r=>r.time.from<=e&&r.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:h,time:{from:p,to:f}},S)=>{const w=p<=i&&f>=i,y=p>i||w||S===0&&i===0,$=Math.min(this.forwardBufferTarget,this.bufferLimit),_=this.preloadOnly&&p<=i+$||f<=i+$;return(h===N.NONE||h===N.PARTIALLY_EJECTED&&y&&_&&this.sourceBuffer&&!Ti(this.sourceBuffer.buffered,i))&&y&&_});if(s===-1)return[];if(t!==xe.BYTE_RANGE)return e.slice(s,s+1);const r=e;let n=0,o=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<r.length&&(n<=c||o<=u);h++){const p=r[h];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status===N.NONE||p.status===N.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type===xe.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=N.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:r,url:n,signal:o,onProgress:d,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Te(o,async function*(){const u=jt(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,u))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const u=await this.fetcher.fetch(n,{range:r,signal:o,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!u)return;const h=new DataView(u);if(this.isActiveLowLatency()){const p=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(h,p)}d&&s.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(h,o),s.segment.status=N.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(u){this.abortActiveSegments([e]),vi(u)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const d of e)d.status=N.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:r,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Te(n,async function*(){const d=jt(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,d),C(window,"online").pipe(Se()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(r,{range:s,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(d){this.abortActiveSegments(e),vi(d)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(yt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:r}=this.downloadAbortController;return{url:i,range:s,signal:r,onProgress:(o,d)=>{if(!r.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:d,signal:r,onSegmentAppendFailed:()=>this.abort(),globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:P.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!yt(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const s=i.toString(),{signal:r}=this.downloadAbortController,n=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,u)=>{if(!r.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:c,loaded:u,signal:r,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:P.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:s,signal:r,onProgress:d,onProgressTasks:n}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:r}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:d}=o;if(o.representationId===t){if(r.aborted){s();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),u=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);u?.byteLength&&(d.status=N.PARTIALLY_FED,o.feedingBytes+=u.byteLength,await this.sourceBufferTaskQueue.append(u),o.fedBytes+=u.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:r,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const d=o.segmentReference.type,c=e.byteLength;for(const u of this.activeSegments){const{segment:h}=u,p=d===xe.BYTE_RANGE,f=p?h.byte.to-h.byte.from+1:c;if(u.representationId!==t||!(!p||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(r.aborted){n();continue}const w=p?h.byte.from-i:0,y=p?h.byte.to-i:e.byteLength,$=w<s,_=y<=s;if(h.status===N.DOWNLOADING&&$&&_){h.status=N.DOWNLOADED;const M=new DataView(e.buffer,e.byteOffset+w,f);this.sourceBufferTaskQueue.append(M,r).then(E=>E&&!r.aborted?this.onSegmentFullyAppended(u,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&$&&(u.loadedBytes=Math.min(f,s-w),u.loadedBytes>u.feedingBytes)){const M=new DataView(e.buffer,e.byteOffset+w+u.feedingBytes,u.loadedBytes-u.feedingBytes),E=u.loadedBytes===f?M:this.containerParser.parseFeedableSegmentChunk(M);E?.byteLength&&(h.status=N.PARTIALLY_FED,u.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,r).then(D=>{if(r.aborted)n();else if(D)u.fedBytes+=E.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=N.FED,Ui(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===N.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=N.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===N.PARTIALLY_FED||e.status===N.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=N.NONE),e.status=N.PARTIALLY_EJECTED):e.status=N.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Te(this.destroyAbortController.signal,async function*(){const o=jt(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async o=>{if(!o)return;const{init:d,dataView:c,segments:u}=o,h=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,h);let p=u;this.isLive&&yt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(e)||this.sourceBuffer.updating)return!1;let s=0,r=1/0,n=-1/0,o=!1;const d=c=>{r=Math.min(r,c.time.from),n=Math.max(n,c.time.to);const u=Ui(c)?c.size??0:c.byte.to-c.byte.from;s+=u};for(const c of this.segments.values())for(const u of c){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;u.status===N.FED&&d(u)}if(o=isFinite(r)&&isFinite(n),!o){s=0,r=1/0,n=-1/0;for(const c of this.segments.values())for(const u of c){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;u.status===N.FED&&d(u)}}if(o=isFinite(r)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const u=this.sourceBuffer.buffered.start(c)*1e3,h=this.sourceBuffer.buffered.end(c)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===N.NONE&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(h)){r=u,n=h;break}}if(o=isFinite(r)&&isFinite(n),!o&&i){s=0,r=1/0,n=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const h of u)h.time.from>e+c&&h.status===N.FED&&d(h)}return o=isFinite(r)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(r,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){const n=this.sourceBuffer.buffered.start(r)*1e3,o=this.sourceBuffer.buffered.end(r)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){s=void 0;break}o>i.time.from&&o<i.time.to&&(s.from=o),n<i.time.to&&n>i.time.from&&(s.to=n)}}s&&s.to-s.from>1&&!this.gaps.some(r=>s&&r.from===s.from&&r.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:P.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),r=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:r})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:r}=s;if(r!==N.FED&&r!==N.PARTIALLY_EJECTED)continue;const n=Math.floor(s.time.from),o=Math.ceil(s.time.to),d=e.some(u=>u.from-t<=n&&u.to+t>=o),c=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);d||(c.length===1||this.gaps.some(u=>u.from===s.time.from||u.to===s.time.to)?s.status=N.PARTIALLY_EJECTED:s.status=N.NONE)}}}var Ei=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},ir=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?Si.HTTP1:e??void 0,s=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:s}},At;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(At||(At={}));class sr{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new AbortController;subscription=new ee;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=ir(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=Te(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ei(t));const i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Rt);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=Te(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?At.HEADER:At.PARAM,range:i,onProgress:s,priority:r="auto",signal:n,measureThroughput:o=!0,isLowLatency:d=!1}={}){let c=e;const u=new Headers;if(i)switch(t){case At.HEADER:{u.append("Range",`bytes=${i.from}-${i.to}`);break}case At.PARAM:{const U=new URL(c,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),c=U.toString();break}default:V(t)}this.requestQuic&&(c=Ei(c));let h=this.abortAllController.signal,p;if(n){const U=new AbortController;if(p=O(C(this.abortAllController.signal,"abort"),C(n,"abort")).subscribe(()=>{try{U.abort()}catch(W){Rt(W)}}),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(W){Rt(W)}h=U.signal}const f=ae(),S=yield fetch(c,{priority:r,headers:u,signal:h}).catch(Rt),w=ae();if(!S)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(w-f),!S.ok||!S.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`));if(this.onHeadersReceived(S.headers),!s&&!o)return p?.unsubscribe(),S.arrayBuffer();const[y,$]=S.body.tee(),_=y.getReader();o&&this.throughputEstimator?.trackStream($,d);let M=0,E=new Uint8Array(0),D=!1;const J=U=>{p?.unsubscribe(),D=!0,Rt(U)},q=Te(h,async function*({done:U,value:W}){if(M===0&&this.lastRequestFirstBytes$.next(ae()-f),h.aborted){p?.unsubscribe();return}if(!U&&W){const L=new Uint8Array(E.length+W.length);L.set(E),L.set(W,E.length),E=L,M+=W.byteLength,s?.(new DataView(E.buffer),M),yield _?.read().then(q,J)}}.bind(this));return yield _?.read().then(q,J),p?.unsubscribe(),D?null:E.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case xe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case xe.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:V(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=Te(this.abortAllController.signal,async function*(e,t,i){if(e.type!==xe.BYTE_RANGE)return null;const{from:s,to:r}=e.initRange;let n=s,o=r,d=!1,c,u;e.indexRange&&(c=e.indexRange.from,u=e.indexRange.to,d=r+1===c,d&&(n=Math.min(c,s),o=Math.max(u,r))),n=Math.min(n,0);const h=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!h)return null;const p=new DataView(h,s-n,r-n+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),S=e.indexRange??t.getIndexRange(f);if(!S)throw new ReferenceError("No way to load representation index");let w;if(d)w=new DataView(h,S.from-n,S.to-S.from+1);else{const $=yield this.fetch(e.url,{range:S,priority:i,measureThroughput:!1});if(!$)return null;w=new DataView($)}const y=t.parseSegments(w,f,S);return{init:f,dataView:new DataView(h),segments:y}}.bind(this));fetchTemplateRepresentation=Te(this.abortAllController.signal,async function*(e,t){if(e.type!==xe.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(n=>({...n,status:N.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Rt=a=>{if(!vi(a))throw a},Et=1e3,ii=(a,e,t)=>t*e+(1-t)*a,hs=(a,e)=>a.reduce((t,i)=>t+i,0)/e,ar=(a,e,t,i)=>{let s=0,r=t;const n=hs(a,e),o=e<i?e:i;for(let d=0;d<o;d++)a[r]>n?s++:s--,r=(a.length+r-1)%a.length;return Math.abs(s)===o};class xi{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new g(e.initial),this.debounced$=new g(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ue(`raw_${t}`),this.smoothedSeries$=new Ue(`smoothed_${t}`),this.reportedSeries$=new Ue(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),r=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>r||this.smoothed<n)&&(Q(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class rr extends xi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ii(this.slow,e,this.params.emaAlphaSlow),this.fast=ii(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class nr extends xi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=hs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ii(this.emaSmoothed,e,this.params.emaAlpha);const i=ar(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class or extends xi{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?ii(this.smoothed,e,this.params.emaAlpha):e}}class Ai{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new rr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new nr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new or({initial:e,label:"liveEdgeDelay",...t})}}const cr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},at=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),dr=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),ur=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,Yi=["timeupdate","progress","play","seeked","stalled","waiting"];var De;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(De||(De={}));let hr=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new ee;representationSubscription=new ee;fetcher;state$=new ne(De.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);currentVideoSegmentLength$=new g(0);currentAudioSegmentLength$=new g(0);error$=new x;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);isLive$=new g(!1);liveDuration$=new g(0);liveAvailabilityStartTime$=new g(void 0);bufferLength$=new g(0);liveLoadBufferLength$=new g(0);livePositionFromPlayer$=new g(0);liveEstimatedDelay;timeInWaiting=0;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new x;gapWatchdogStarted=!1;gapWatchdogSubscription;stallWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new sr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ai.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=Te(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Oe(t,i,le.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(De.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(De.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:P.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=Te(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:P.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Xa(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:P.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:r,codecs:n})=>!!(this.element?.canPlayType?.(r)&&at()?.isTypeSupported?.(`${r}; codecs="${n}"`)||s===me.TEXT);return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,r])=>[s,r.filter(i)]))}}.bind(this));async seekLive(e){v(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=Oe(this.manifestUrlString,t,le.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=Te(this.destroyController.signal,async function*(e,t,i){v(this.manifest),v(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(De.REPRESENTATIOS_READY);const s=f=>{this.representationSubscription.add(C(f,"error").pipe(oe(S=>!!this.element?.played.length)).subscribe(S=>{this.error$.next({id:"VideoSource",category:P.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:S})}))};this.source=this.tuning.useManagedMediaSource?ur():new MediaSource;const r=document.createElement("source");if(s(r),r.src=URL.createObjectURL(this.source),this.element.appendChild(r),this.tuning.useManagedMediaSource&&ls())if(i){const f=document.createElement("source");s(f),f.type="application/x-mpegurl",f.src=i.url,this.element.appendChild(f)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Hi(me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],A(t)&&(this.audioBufferManager=new Hi(me.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Bt(Et).subscribe(f=>{if(this.element?.paused){const S=Ii(this.manifestUrlString,le.DASH_CMAF_OFFSET_P);this.manifestUrlString=Oe(this.manifestUrlString,S+Et,le.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(O(...Yi.filter(f=>f!=="waiting").map(f=>C(this.element,f))).pipe(T(f=>this.element?Mt(this.element.buffered,this.element.currentTime*1e3):0),de(),oe(f=>!!f),Nt(f=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(oe(S=>this.isActiveLowLatency&&!!S)).subscribe(S=>this.liveEstimatedDelay.next(S))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(S=>{if(!this.isActiveLowLatency)return;const w=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,$=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,_=S-w;let M=1+Math.sign(_)*$;Math.abs(_)<y?M=1:Math.abs(_)>y*2&&(M=1+Math.sign(_)*$*2),cr(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(S=>{let w=0;if(S){const y=(this.element?.currentTime??0)*1e3;w=Math.min(...this.bufferManagers.map(_=>_.getLiveSegmentsToLoadState(this.manifest)?.to??y))-y}this.liveLoadBufferLength$.getValue()!==w&&this.liveLoadBufferLength$.next(w)}));let f=0;this.representationSubscription.add(Le({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ks(Et)).subscribe(async({liveLoadBufferLength:S,bufferLength:w})=>{if(v(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,$=Ii(this.manifestUrlString,le.DASH_CMAF_OFFSET_P),_=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,M=Math.min(_,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,J=this.isActiveLowLatency?w:S;let q=Ve.None;if(this.isActiveLowLatency?q=Ve.ActiveLowLatency:J<M+D&&J>=M?q=Ve.LiveWithTargetOffset:$!==0&&J<M&&(q=Ve.LiveForwardBuffering),isFinite(S)&&(f=S>f?S:f),q===Ve.LiveForwardBuffering||q===Ve.LiveWithTargetOffset){const U=f-(M+E),W=this.normolizeLiveOffset(Math.trunc($+U/y)),L=Math.abs(W-$);let I;!S||L<=this.tuning.dashCmafLive.offsetCalculationError?I=$:W>0&&L>this.tuning.dashCmafLive.offsetCalculationError?I=W:I=0,this.manifestUrlString=Oe(this.manifestUrlString,I,le.DASH_CMAF_OFFSET_P)}q!==Ve.None&&q!==Ve.ActiveLowLatency&&(f=0,this.updateLive())}))}const o=O(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe(T(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),d=O(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe(T(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add(O(this.forceEnded$,Le({allBuffersFull:o,someBufferEnded:d}).pipe(oe(({allBuffersFull:f,someBufferEnded:S})=>f&&S))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{this.source?.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:P.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(O(...this.bufferManagers.map(f=>f.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(f=>this.source?.addEventListener("sourceopen",f)));const c=this.manifest.duration??0,u=(f,S)=>Math.max(f,S.duration??0),h=this.manifest.representations.audio.reduce(u,c),p=this.manifest.representations.video.reduce(u,c);(h||p)&&(this.source.duration=Math.max(h,p)/1e3),this.audioBufferManager&&A(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(De.REPRESENTATIOS_READY)}.bind(this));initBuffer(){v(this.element),this.state$.setState(De.RUNNING),this.subscription.add(O(...Yi.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:P.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const e=()=>{if(this.element){if(this.timeInWaiting+=Et,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Bt(Et).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:P.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{[me.VIDEO]:this.videoBufferManager,[me.AUDIO]:this.audioBufferManager,[me.TEXT]:null}[e]?.switchTo(t)}seek(e,t){v(this.element),v(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ti(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(De.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Bt(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:P.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from-s<=t&&n.to+s>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i)+10;r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class lr{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class fr{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,r=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:s,y:r,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var pr=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2
|
|
39
|
-
|
|
33
|
+
[best track] ${L?.quality}
|
|
34
|
+
[selected track] ${A?.quality}
|
|
35
|
+
`});let D=A&&d&&d.history[A.id]&&za()-d.history[A.id]<=i.trackCooldown&&(!d.last||A.id!==d.last.id);if(A?.id&&d&&!D&&d.recordSelection(A),D&&d?.last){let I=d.last;return d?.recordSwitch(I),c({message:`
|
|
36
|
+
[last selected] ${I?.quality}
|
|
37
|
+
`}),I}return d?.recordSwitch(A),A},Fe=Ao;var Q=n=>new URL(n).hostname;import{assertNever as ts,assertNonNullable as is,combine as jo,debounce as qo,ErrorCategory as rs,filter as zo,filterChanged as Ko,isNonNullable as Vr,map as _i,merge as as,observableFrom as Jo,Subscription as Xo,ValueSubject as Or,videoQualityToHeight as Zo,videoSizeToQuality as ed}from"@vkontakte/videoplayer-shared";var Ka=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"))},X=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!Ka(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return Ka(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Bi,isNullable as Lo,assertNonNullable as Dt}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ja,assertNonNullable as Ci,now as wo}from"@vkontakte/videoplayer-shared";function G(){return wo()}function Dr(n){return G()-n}function Mr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Xa(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function ht(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,l,c,h=!1,p="arraybuffer",m=7e3,y=2e3,f=()=>{if(u)return;Ci(l);let w=Dr(l),N;if(w<y){N=y-w,setTimeout(f,N);return}y*=2,y>m&&(y=m),s&&s.abort(),s=new r,V()},S=w=>(a=w,E),b=w=>(c=w,E),P=()=>(p="json",E),g=()=>{if(!u){if(--d>=0){f(),i&&i();return}u=!0,c&&c(),t&&t()}},T=w=>(h=w,E),V=()=>{l=G(),s=new r,s.open("get",n);let w=0,N,W=0,pe=()=>(Ci(l),Math.max(l,Math.max(N||0,W||0)));if(a&&s.addEventListener("progress",k=>{let C=G();a.updateChunk&&k.loaded>w&&(a.updateChunk(pe(),k.loaded-w),w=k.loaded,N=C)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>g())),s.addEventListener("load",()=>{if(u)return;Ci(s);let k=s.status;if(k>=200&&k<300){if(s.response.byteLength&&a){let C=s.response.byteLength-w;C&&a.updateChunk&&a.updateChunk(pe(),C)}s.responseType==="json"&&!Object.values(s.response).length?g():(c&&c(),e(s.response))}else g()}),s.addEventListener("error",()=>{g()}),h){let k=()=>{Ci(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=G(),s.removeEventListener("readystatechange",k))};s.addEventListener("readystatechange",k)}return s.responseType=p,s.send(),E},E={withBitrateReporting:S,withParallel:T,withJSONResponse:P,withRetryCount:w=>(d=w,E),withRetryInterval:(w,N)=>(Ja(w)&&(y=w),Ja(N)&&(m=N),E),withTimeout:w=>(o=w,E),withFinally:b,send:V,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return E}var Lt=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 a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(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 Rt=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}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=G(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=G()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ht(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=G()}_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=G();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 a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Vi=1e4,Cr=3;var Ro=6e4,Do=10,Mo=1,Co=500,Mt=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Lt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Mr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;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=Mr(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}`),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&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bi(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=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 s=()=>{Xa(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Rt(Cr,Vi,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,a=!1,s=null,o=null,u=null,d=null,l=!1,c=()=>{let g=a&&(!l||l===this.rep);return g||t("Not running!"),g},h=(g,T,V)=>{u&&u.abort(),u=ht(this.urlResolver.resolve(g,!1),T,V,()=>this._retryCallback()).withTimeout(Vi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Cr).withFinally(()=>{u=null}).send()},p=(g,T,V)=>{Dt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),T,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=g=>{let T=i.playbackRate;i.playbackRate!==g&&(t(`Playback rate switch: ${T}=>${g}`),i.playbackRate=g)},y=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),f()},f=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=G()-1e4,L=0;for(let D=0;D<this.bufferStates.length;D++){let I=this.bufferStates[D];g=Math.min(g,I.buf),I.ts<V&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${g} drop=${L} jitter=${this.sourceJitter}`);let A=g-Mo;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?m(1.15):A>1?m(1.1):A>.3?m(1.05):m(1)}},S=g=>{let T,V=()=>T&&T.start?T.start.length:0,L=k=>T.start[k]/1e3,A=k=>T.dur[k]/1e3,D=k=>T.fragIndex+k,I=(k,C)=>({chunkIdx:D(k),startTS:L(k),dur:A(k),discontinuity:C}),E=()=>{let k=0;if(T&&T.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,H=C;this.sourceJitter>1&&(H+=this.sourceJitter-1);let Z=T.dur.length-1;for(;Z>=0&&(H-=T.dur[Z],!(H<=0));--Z);k=Math.min(Z,T.dur.length-1-F),k=Math.max(k,0)}return I(k,!0)},w=k=>{let C=V();if(!(C<=0)){if(Bi(k)){for(let F=0;F<C;F++)if(L(F)>k)return I(F)}return E()}},N=k=>{let C=V(),F=k?k.chunkIdx+1:0,H=F-T.fragIndex;if(!(C<=0)){if(!k||H<0||H-C>Do)return t(`Resync: offset=${H} bChunks=${C} chunk=`+JSON.stringify(k)),E();if(!(H>=C))return I(F-T.fragIndex,!1)}},W=(k,C,F)=>{d&&d.abort(),d=ht(this.urlResolver.resolve(k,!0,this.lowLatency),C,F,()=>this._retryCallback()).withTimeout(Vi).withRetryCount(Cr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,C)=>{W(g,F=>{if(!c())return;T=F;let H=!!T.lowLatency;H!==this.lowLatency&&y(H);let Z=0;for(let De=0;De<T.dur.length;++De)Z+=T.dur[De];Z>0&&(Dt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,k(w(C))},()=>this._handleNetworkError())},nextChunk:N}},b=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),Dt(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:g=>{let{videoElement:T,logger:V}=this.params,L=S(e.jidxUrl),A,D,I,E,w=0,N,W,pe,k=()=>{N&&(clearTimeout(N),N=void 0);let O=Math.max(Co,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=w+O,te=G(),he=Math.min(1e4,ee-te);w=te;let xe=()=>{d||c()&&L.seek(()=>{c()&&(w=G(),C(),k())})};he>0?N=window.setTimeout(()=>{this.paused?k():xe()},he):xe()},C=()=>{let O;for(;O=L.nextChunk(E);)E=O,cr(O);let ee=L.nextChunk(I);if(ee){if(I&&ee.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?k():(b(),this._initPlayerWith(e));return}De(ee)}else k()},F=(O,ee)=>{if(!c()||!this.sourceBuffer)return;let te,he,xe,It=ie=>{window.setTimeout(()=>{c()&&F(O,ee)},ie)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),It(100);else{let ie=G(),Me=T.currentTime;!this.paused&&T.buffered.length>1&&W===Me&&ie-pe>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),W!==Me&&(W=Me,pe=ie);let me=this._getBufferSizeSec();if(me>30)V(`Buffered ${me} seconds; delaying appendBuffer`),It(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:ie,buf:me}),f(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(ve){if(ve.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),xe=this.sourceBuffer.buffered.length,xe!==0&&(te=this.sourceBuffer.buffered.start(0),he=Me,he-te>4&&this.sourceBuffer.remove(te,he-3)),It(1e3);else throw ve}}},H=()=>{D&&A&&(V([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(I)]),F(D,function(){D=null,C()}))},Z=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),De=O=>{c()&&p(Z(O),(ee,te)=>{if(c()){if(te/=1e3,D=ee,I=O,s=O.startTS,te){let he=Math.min(10,O.dur/te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}H()}},()=>this._handleNetworkError())},cr=O=>{c()&&(Dt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(O),!1)))},Ei=O=>{c()&&(e.cachedHeader=O,F(O,()=>{A=!0,H()}))};a=!0,L.seek(O=>{if(c()){if(w=G(),!O){k();return}E=O,!Lo(g)||O.startTS>g?De(O):(I=O,C())}},g),e.cachedHeader?Ei(e.cachedHeader):h(e.headerUrl,Ei,()=>this._handleNetworkError())},stop:b,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Bi(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,Dt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bi(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),m=c/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(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,p)=>{let m=G();if(this.chunkRateEstimator.addInterval(h,m,p)){let f=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:f}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),s=-1/0,o,u=!0,d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Dr(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&d(),p},notifySwitch:c=>{let h=G();c<o&&(s=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=ht(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Vi).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;X(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(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))},Ro))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Bo,filter as Za,fromEvent as Vo,interval as Oo,isHigher as _o,isInvariantQuality as No,isLower as Fo,merge as Uo,Subject as es,Subscription as Ho}from"@vkontakte/videoplayer-shared";var Br=class{constructor(){this.onDroopedVideoFramesLimit$=new es;this.subscription=new Ho;this.playing=!1;this.tracks=[];this.forceChecker$=new es;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&&!No(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&_o(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Vo(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Oo(this.droppedFramesChecker.checkTime).pipe(Za(()=>this.playing),Za(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Bo(this.droppedFramesChecker.checkTime)),i=Uo(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])=>Fo(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}},Oi=Br;import{map as Qo,Observable as Go}from"@vkontakte/videoplayer-shared";import{fromEvent as Wo}from"@vkontakte/videoplayer-shared";var Ct=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Yo=(n,e)=>new Go(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Ct()))},{...i,...e});r.observe(n);let a=Wo(document,"visibilitychange").pipe(Qo(s=>!document.hidden||Ct())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),ue=Yo;var td=["paused","playing","ready"],id=["paused","playing","ready"],Bt=class{constructor(e){this.subscription=new Xo;this.videoState=new $("stopped");this.representations$=new Or([]);this.textTracksManager=new oe;this.droppedFramesManager=new Oi;this.maxSeekBackTime$=new Or(1/0);this.zeroTime$=new Or(void 0);this.liveOffset=new Pe;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:rs.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=_e(r.name)??ed(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let d={id:a,quality:s,bitrate:o,size:u};i.push({track:d,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),Vr(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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),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 s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(id.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&td.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Y(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(Y(this.params.source.url,u))}return;default:return ts(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:rs.WTF,message:"DashLiveProvider internal logic error",thrown:r})};as(this.videoState.stateChangeStarted$.pipe(_i(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_i(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=q(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=J(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(_i(r=>r.map(({track:a})=>a)))}),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(Ko(),_i(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(jo({zeroTime:this.zeroTime$.pipe(zo(Vr)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Te(this.video,this.params.desiredState.isLooped,t)).add(K(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ne(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Zo(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).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 ts(r.to)}},t)).add(as(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Jo(["init"])).pipe(qo(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),z(this.video)}createLiveDashPlayer(){let e=new Mt({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Vr(t)?t:Fe(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let d=e.find(({track:l})=>l.id===a)?.representation;is(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;is(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",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Y(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var ss=Bt;var Ue=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Fd,assertNonNullable as Qs,debounce as Ud,ErrorCategory as Xr,filter as Hd,filterChanged as Gs,fromEvent as Qd,isLowerOrEqual as Ws,isNonNullable as Gd,videoSizeToQuality as Ys,map as Zr,merge as zi,observableFrom as Wd,observeElementSize as Yd,once as jd,Subscription as qd,ValueSubject as js}from"@vkontakte/videoplayer-shared";var Vt=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as zr,assertNonNullable as at,combine as Vs,ErrorCategory as Qe,filter as Gi,filterChanged as Md,fromEvent as St,interval as Kr,isNonNullable as Os,map as Jr,merge as vt,Subject as _s,Subscription as Ns,tap as Cd,throttle as Bd,ValueSubject as ae}from"@vkontakte/videoplayer-shared";import{assertNever as rd,CurrentClientBrowser as ad,ErrorCategory as ns,getCurrentBrowser as sd,Subject as os}from"@vkontakte/videoplayer-shared";var nd=16,ds=!1;try{ds=sd().browser===ad.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=nd}catch(n){console.error(n)}var _r=class{constructor(e){this.bufferFull$=new os;this.error$=new os;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ns.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 a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;ds&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:ns.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:rd(t)}}},us=_r;var Nr=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 bt,assertNever as kd,assertNonNullable as we,ErrorCategory as gt,fromEvent as Gr,getExponentialDelay as Wr,once as Pd,isNonNullable as As,isNullable as $e,Subject as Ad,Subscription as wd,ValueSubject as ai}from"@vkontakte/videoplayer-shared";var B=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,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let 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 mt=class extends B{};var Ot=class extends B{};var _t=class extends B{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Nt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ft=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ut=class extends B{constructor(t,i){super(t,i);this.data=this.content}};var U=class extends B{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Je=class extends U{constructor(t,i){super(t,i);this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,o=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:u,SAPType:d,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Ht=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Qt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gt=class extends U{constructor(t,i){super(t,i);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 Wt=class extends U{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Yt=class extends U{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var jt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qt=class extends U{constructor(t,i){super(t,i);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 zt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jt=class extends U{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var Xt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zt=class extends U{constructor(t,i){super(t,i);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 ei=class extends U{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 ti=class extends U{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 dd={ftyp:_t,moov:Nt,moof:Ft,mdat:Ut,sidx:Je,trak:Ht,mdia:jt,mfhd:Jt,tkhd:qt,traf:Xt,tfhd:Zt,tfdt:ei,trun:ti,minf:zt,sv3d:Qt,st3d:Gt,prhd:Wt,proj:Kt,equi:Yt,uuid:Ot,unknown:mt},Xe=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch{break}return t}createBox(e,t){let i=dd[e];return i?new i(t,new n):new mt(t,new n)}};var ft=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 ld=new TextDecoder("ascii"),cd=n=>ld.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",pd=n=>{let e=new Je(n,new Xe),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},hd=(n,e)=>{let i=new Xe().parse(n),r=new ft(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,c)},md=(n,e)=>{let i=new Xe().parse(n),a=new ft(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,h)=>c+h,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},fd=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 Xe().parse(n),r=new ft(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.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},ls={validateData:cd,parseInit:fd,getIndexRange:()=>{},parseSegments:pd,parseFeedableSegmentChunk:hd,getSegmentEndTime:md};import{assertNonNullable as Ur,isNonNullable as ms,isNullable as gd}from"@vkontakte/videoplayer-shared";import{assertNever as bd}from"@vkontakte/videoplayer-shared";var cs={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"}},ps=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=ii(n,t),r=i in cs,a=r?cs[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,l=ii(u),c=d*2**((o-1)*8)+l,h=t+o,p;return h+c>n.byteLength?p=new DataView(n.buffer,n.byteOffset+h):p=new DataView(n.buffer,n.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},ii=(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},be=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ii(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:bd(e)}},Ze=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=ps(i);if(!e(r))return;r.type==="master"&&Ze(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},hs=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=ps(n);return Ze(r.value,({tag:a,type:s,value:o})=>(a===17143?e=be(o,s):a===17026?t=be(o,s):a===17029&&(i=be(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var fs=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Sd=[231,22612,22743,167,171,163,160,175],vd=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,l=!1,c=0;return Ze(n,({tag:h,type:p,value:m,valueSize:y})=>{if(h===21419){let f=be(m,p);d=ii(f)}else h!==21420&&(d=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+y):h===357149030?a=!0:h===290298740?s=!0:h===2807729?i=be(m,p):h===17545?r=be(m,p):h===21420&&d===475249515?u=be(m,p):h===374648427?Ze(m,({tag:f,type:S,value:b})=>f===30321?(l=be(b,S)===1,!1):!0):a&&s&&fs.includes(h)&&(o=!0),!o}),Ur(e,"Failed to parse webm Segment start"),Ur(t,"Failed to parse webm Segment end"),Ur(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:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},yd=n=>{if(gd(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Td=(n,e)=>{let t=!1,i=!1,r=o=>ms(o.time)&&ms(o.position),a=[],s;return Ze(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=be(d,u));break;case 183:break;case 241:s&&(s.position=be(d,u));break;default:t&&fs.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:l}=o,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Id=n=>{let e=0,t=!1;try{Ze(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Sd.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},bs={validateData:hs,parseInit:vd,getIndexRange:yd,parseSegments:Td,parseFeedableSegmentChunk:Id};import{isNonNullable as Ss,isNullable as vs}from"@vkontakte/videoplayer-shared";var gs=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var ys=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.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,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},et=(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,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>vs(a)?o:vs(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Is=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=a.querySelector("BaseURL")?.textContent?.trim()??"",u=s.children,d=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,h,p=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),f=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)h=ys(p);else if(m){let g=ys(m);Ss(g)&&(h=g)}else f&&(h=parseInt(f,10));let S=0,b=a.getAttribute("profiles")?.split(",")??[],P=b.includes("urn:webm:dash:profile:webm-on-demand:2012")||b.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let g of u){let T=g.getAttribute("mimeType"),V=g.getAttribute("codecs"),L=g.getAttribute("contentType")??T?.split("/")[0],A=g.getAttribute("profiles")?.split(",")??[],D=g.querySelectorAll("Representation"),I=g.querySelector("SegmentTemplate");if(L==="text"){for(let E of D){let w=E.getAttribute("id")||"",N=g.getAttribute("lang"),W=g.getAttribute("label"),pe=E.querySelector("BaseURL")?.textContent?.trim()??"",k=new URL(pe||o,e).toString(),C=w.includes("_auto");r.text.push({id:w,lang:N,label:W,isAuto:C,kind:"text",url:k})}continue}for(let E of D){let w=E.getAttribute("mimeType")??T,N=E.getAttribute("codecs")??V??"",W=E.getAttribute("contentType")??w?.split("/")[0]??L,pe=g.getAttribute("profiles")?.split(",")??[],k=parseInt(E.getAttribute("width")??"",10),C=parseInt(E.getAttribute("height")??"",10),F=parseInt(E.getAttribute("bandwidth")??"",10)/1e3,H=E.getAttribute("frameRate")??"",Z=E.getAttribute("quality")??void 0,De=H?gs(H):void 0,cr=E.getAttribute("id")??(S++).toString(10),Ei=W==="video"?`${C}p`:W==="audio"?`${F}Kbps`:N,O=`${cr}@${Ei}`,ee=E.querySelector("BaseURL")?.textContent?.trim()??"",te=new URL(ee||o,e).toString(),he=[...b,...A,...pe],xe,It=E.querySelector("SegmentBase"),ie=E.querySelector("SegmentTemplate")??I;if(It){let me=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ve,pr]=me.split("-").map(ut=>parseInt(ut,10)),Ce={from:ve,to:pr},Et=E.querySelector("SegmentBase")?.getAttribute("indexRange"),[hr,xi]=Et?Et.split("-").map(ut=>parseInt(ut,10)):[],xt=Et?{from:hr,to:xi}:void 0;xe={type:"byteRange",url:te,initRange:Ce,indexRange:xt}}else if(ie){let me={representationId:E.getAttribute("id")??void 0,bandwidth:E.getAttribute("bandwidth")??void 0},ve=parseInt(ie.getAttribute("timescale")??"",10),pr=ie.getAttribute("initialization")??"",Ce=ie.getAttribute("media"),Et=parseInt(ie.getAttribute("startNumber")??"",10)??1,hr=et(pr,me);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let xi=ie.querySelectorAll("SegmentTimeline S")??[],xt=[],ut=0,mr="",fr=0;if(xi.length){let ki=Et,fe=0;for(let lt of xi){let ye=parseInt(lt.getAttribute("d")??"",10),je=parseInt(lt.getAttribute("r")??"",10)||0,Pi=parseInt(lt.getAttribute("t")??"",10);fe=Number.isFinite(Pi)?Pi:fe;let br=ye/ve*1e3,Nn=fe/ve*1e3;for(let Ai=0;Ai<je+1;Ai++){let Fn=et(Ce,{...me,segmentNumber:ki.toString(10),segmentTime:(fe+Ai*ye).toString(10)}),ma=(Nn??0)+Ai*br,Un=ma+br;ki++,xt.push({time:{from:ma,to:Un},url:Fn})}fe+=(je+1)*ye,ut+=(je+1)*br}fr=fe/ve*1e3,mr=et(Ce,{...me,segmentNumber:ki.toString(10),segmentTime:fe.toString(10)})}else if(Ss(h)){let fe=parseInt(ie.getAttribute("duration")??"",10)/ve*1e3,lt=Math.ceil(h/fe),ye=0;for(let je=1;je<lt;je++){let Pi=et(Ce,{...me,segmentNumber:je.toString(10),segmentTime:ye.toString(10)});xt.push({time:{from:ye,to:ye+fe},url:Pi}),ye+=fe}fr=ye,mr=et(Ce,{...me,segmentNumber:lt.toString(10),segmentTime:ye.toString(10)})}let _n={time:{from:fr,to:1/0},url:mr};xe={type:"template",baseUrl:te,segmentTemplateUrl:Ce,initUrl:hr,totalSegmentsDurationMs:ut,segments:xt,nextSegmentBeyondManifest:_n,timescale:ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!W||!w)continue;let Me={video:"video",audio:"audio",text:"text"}[W];Me&&r[Me].push({id:O,kind:Me,segmentReference:xe,profiles:he,duration:h,bitrate:F,mime:w,codecs:N,width:k,height:C,fps:De,quality:Z})}}return{dynamic:d,liveAvailabilityStartTime:c,duration:h,container:P,representations:r}};import{videoSizeToQuality as xd}from"@vkontakte/videoplayer-shared";var Es=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?_e(a):void 0)??xd({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},xs=({id:n,bitrate:e})=>({id:n,bitrate:e}),ks=(n,e,t)=>{let i=e.indexOf(t);return n.at(Math.round(n.length*i/e.length))??n.at(-1)},Ps=({id:n,lang:e,label:t,url:i,isAuto:r})=>({id:n,url:i,isAuto:r,type:"internal",language:e,label:t}),Qr=n=>"url"in n,tt=n=>n.type==="template",ri=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var si=class{constructor(e,t,i,r,{fetcher:a,tuning:s,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){this.currentSegmentLength$=new ai(0);this.onLastSegment$=new ai(!1);this.fullyBuffered$=new ai(!1);this.playingRepresentation$=new ai(void 0);this.playingRepresentationInit$=new ai(void 0);this.error$=new Ad;this.gaps=[];this.subscription=new wd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=bt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);we(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new us(this.sourceBuffer),this.subscription.add(Gr(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:gt.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add(Gr(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,Nr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);we(i,"No init buffer for starting representation"),we(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(a))}.bind(this));this.switchTo=bt(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);we(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if($e(r)||$e(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),we(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);let a=this.getCurrentPosition();As(a)&&(this.isLive||(i.forEach(s=>s.status="none"),this.pruneBuffer(a,1/0,!0)),this.maintain(a))}.bind(this));this.seekLive=bt(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let u=e.find(c=>c.id===o);u&&this.representations.set(o,u);let d=this.representations.get(o);if(!d||!tt(d.segmentReference))return;let l=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,l)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);we(i);let r=this.segments.get(t);we(r,"No segments for starting representation");let a=this.initData.get(t);if(we(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let s=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),s&&(yield this.sourceBufferTaskQueue.remove(s.from*1e3,s.to*1e3,this.destroyAbortController.signal)),this.searchGaps(r,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=a,this.tuning=s,this.compatibilityMode=d,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!l?.dynamic,this.container=i,i){case"mp4":this.containerParser=ls;break;case"webm":this.containerParser=bs;break;default:kd(i)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if($e(e)||$e(this.downloadingRepresentationId)||$e(this.playingRepresentationId)||$e(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(we(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=Ue(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&Nr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ue(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let l=o.at(0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Ue(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;As(t.duration)&&t.duration-i>0&&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=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.representations[this.kind].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){for(let t of e?.representations[this.kind].values()??[]){if(!t||!tt(t.segmentReference))return;let i=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),r=this.segments.get(t.id)??[],a=r.at(-1)?.time.to??0,s=i?.findIndex(o=>Math.floor(a)>=Math.floor(o.time.from)&&Math.floor(a)<=Math.floor(o.time.to));if(s===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=i.slice(s+1);this.segments.set(t.id,[...r,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let i=t.segmentReference;if(!tt(i))return;let r=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),a=et(i.segmentTemplateUrl,{segmentTime:r}),s=this.segments.get(t.id)??[],o=s.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!s.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||s.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:a})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){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=e.findIndex(({status:c,time:{from:h,to:p}},m)=>{let y=h<=i&&p>=i,f=h>i||y||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),b=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&f&&b&&this.sourceBuffer&&!Vt(this.sourceBuffer.buffered,i))&&f&&b});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||o<=l);c++){let h=a[c];if(s+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type==="template"?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:a,url:s,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await bt(o,async function*(){let l=Wr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(this.isActiveLowLatency()){let h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),ri(l)||this.failedDownloads++}}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:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await bt(s,async function*(){let u=Wr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),Gr(window,"online").pipe(Pd()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ri(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(tt(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:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!tt(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:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}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:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d,this.isLive);l?.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let l of this.activeSegments){let{segment:c}=l,h=u==="byteRange",p=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let y=h?c.byte.from-i:0,f=h?c.byte.to-i:e.byteLength,S=y<r,b=f<=r;if(c.status==="downloading"&&S&&b){c.status="downloaded";let P=new DataView(e.buffer,e.byteOffset+y,p);this.sourceBufferTaskQueue.append(P,a).then(g=>g&&!a.aborted?this.onSegmentFullyAppended(l,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(l.loadedBytes=Math.min(p,r-y),l.loadedBytes>l.feedingBytes)){let P=new DataView(e.buffer,e.byteOffset+y+l.feedingBytes,l.loadedBytes-l.feedingBytes),g=l.loadedBytes===p?P:this.containerParser.parseFeedableSegmentChunk(P);g?.byteLength&&(c.status="partially_fed",l.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,a).then(T=>{if(a.aborted)s();else if(T)l.fedBytes+=g.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<p)return;s()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Qr(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"&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||=s,a===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",s=(!i&&this.failedDownloads>0?bt(this.destroyAbortController.signal,async function*(){let o=Wr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;let{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&tt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let l=Qr(d)?d.size??0:d.byte.to-d.byte.from;r+=l};for(let d of this.segments.values())for(let l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(let h of this.segments.values())for(let p of h)if(p.status==="none"&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)){a=l,s=c;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=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+d&&c.status==="fed"&&u(c)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:gt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if($e(this.sourceBuffer)||$e(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=s&&l.to+t>=o),d=e.filter(l=>s>=l.from-t&&s<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var ni=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var ws=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 oi,assertNever as $s,fromEvent as Ls,merge as $d,now as Yr,Subscription as Ld,ValueSubject as jr}from"@vkontakte/videoplayer-shared";var Ni=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new jr(void 0);this.lastConnectionReused$=new jr(void 0);this.lastRequestFirstBytes$=new jr(void 0);this.abortAllController=new AbortController;this.subscription=new Ld;this.fetchManifest=oi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ni(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(di);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=oi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){let d=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(d,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),d=A.toString();break}default:$s(t)}this.requestQuic&&(d=ni(d));let c=this.abortAllController.signal,h;if(s){let A=new AbortController;if(h=$d(Ls(this.abortAllController.signal,"abort"),Ls(s,"abort")).subscribe(()=>{try{A.abort()}catch(D){di(D)}}),this.abortAllController.signal.aborted||s.aborted)try{A.abort()}catch(D){di(D)}c=A.signal}let p=Yr(),m=yield fetch(d,{priority:a,headers:l,signal:c}).catch(di),y=Yr();if(!m)return h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-p),!m.ok||!m.body)return h?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!o)return h?.unsubscribe(),m.arrayBuffer();let[f,S]=m.body.tee(),b=f.getReader();o&&this.throughputEstimator?.trackStream(S,u);let P=0,g=new Uint8Array(0),T=!1,V=A=>{h?.unsubscribe(),T=!0,di(A)},L=oi(c,async function*({done:A,value:D}){if(P===0&&this.lastRequestFirstBytes$.next(Yr()-p),c.aborted){h?.unsubscribe();return}if(!A&&D){let I=new Uint8Array(g.length+D.length);I.set(g),I.set(D,g.length),g=I,P+=D.byteLength,r?.(new DataView(g.buffer),P),yield b?.read().then(L,V)}}.bind(this));return yield b?.read().then(L,V),h?.unsubscribe(),T?null:g.buffer}.bind(this));this.fetchByteRangeRepresentation=oi(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-s,a-s+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let y;if(u)y=new DataView(c,m.from-s,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;y=new DataView(S)}let f=t.parseSegments(y,p,m);return{init:p,dataView:new DataView(c),segments:f}}.bind(this));this.fetchTemplateRepresentation=oi(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(s=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){let{type:t,reused:i}=ws(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:$s(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},di=n=>{if(!ri(n))throw n};var it=(n,e,t)=>t*e+(1-t)*n,qr=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Rs=(n,e,t,i)=>{let r=0,a=t,s=qr(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as Rd,ValueSubject as Ds}from"@vkontakte/videoplayer-shared";var He=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 Ds(e.initial),this.debounced$=new Ds(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new j(`raw_${t}`),this.smoothedSeries$=new j(`smoothed_${t}`),this.reportedSeries$=new j(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,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),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(Rd(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 Fi=class extends He{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=it(this.slow,t,this.params.emaAlphaSlow),this.fast=it(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var Ui=class extends He{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=qr(this.pastMeasures,this.takenMeasures);this.emaSmoothed=it(this.emaSmoothed,t,this.params.emaAlpha);let r=Rs(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var Hi=class extends He{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?it(this.smoothed,t,this.params.emaAlpha):t}};var rt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fi({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ui({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Hi({initial:e,label:"liveEdgeDelay",...t})}};var Ms=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Le=()=>window.ManagedMediaSource||window.MediaSource,Qi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Cs=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Bs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Fs=["timeupdate","progress","play","seeked","stalled","waiting"];var Wi=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ns;this.representationSubscription=new Ns;this.state$=new $("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new _s;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.isLive$=new ae(!1);this.liveDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new _s;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=zr(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Y(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Qe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=zr(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(r=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Qe.NETWORK,message:"Failed to load manifest",thrown:r})});if(!e)return null;let t;try{t=Is(e??"",this.manifestUrlString)}catch(r){this.error$.next({id:"ManifestParsing",category:Qe.PARSER,message:"Failed to parse MPD manifest",thrown:r})}if(!t)return null;let i=({kind:r,mime:a,codecs:s})=>!!(this.element?.canPlayType?.(a)&&Le()?.isTypeSupported?.(`${a}; codecs="${s}"`)||r==="text");return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([r,a])=>[r,a.filter(i)]))}}.bind(this));this.initRepresentations=zr(this.destroyController.signal,async function*(e,t,i){at(this.manifest),at(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(St(p,"error").pipe(Gi(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:Qe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Bs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Qi())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new si("video",this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],Os(t)&&(this.audioBufferManager=new si("audio",this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Kr(1e3).subscribe(p=>{if(this.element?.paused){let m=Tr(this.manifestUrlString,2);this.manifestUrlString=Y(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(vt(...Fs.filter(p=>p!=="waiting").map(p=>St(this.element,p))).pipe(Jr(p=>this.element?Ue(this.element.buffered,this.element.currentTime*1e3):0),Md(),Gi(p=>!!p),Cd(p=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(Gi(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;let y=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,f=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,b=m-y,P=1+Math.sign(b)*S;Math.abs(b)<f?P=1:Math.abs(b)>f*2&&(P=1+Math.sign(b)*S*2),Ms(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let y=0;if(m){let f=(this.element?.currentTime??0)*1e3;y=Math.min(...this.bufferManagers.map(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==y&&this.liveLoadBufferLength$.next(y)}));let p=0;this.representationSubscription.add(Vs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Bd(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:y})=>{if(at(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,S=Tr(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),g=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,V=this.isActiveLowLatency?y:m,L=3;if(this.isActiveLowLatency?L=0:V<P+T&&V>=P?L=1:S!==0&&V<P&&(L=2),isFinite(m)&&(p=m>p?m:p),L===2||L===1){let A=p-(P+g),D=this.normolizeLiveOffset(Math.trunc(S+A/f)),I=Math.abs(D-S),E;!m||I<=this.tuning.dashCmafLive.offsetCalculationError?E=S:D>0&&I>this.tuning.dashCmafLive.offsetCalculationError?E=D:E=0,this.manifestUrlString=Y(this.manifestUrlString,E,2)}L!==3&&L!==0&&(p=0,this.updateLive())}))}let o=vt(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Jr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),u=vt(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Jr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(vt(this.forceEnded$,Vs({allBuffersFull:o,someBufferEnded:u}).pipe(Gi(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Qe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(vt(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let d=this.manifest.duration??0,l=(p,m)=>Math.max(p,m.duration??0),c=this.manifest.representations.audio.reduce(l,d),h=this.manifest.representations.video.reduce(l,d);(c||h)&&(this.source.duration=Math.max(c,h)/1e3),this.audioBufferManager&&Os(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Kr(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Qe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ni({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=rt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){at(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=Y(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){at(this.element),this.state$.setState("running"),this.subscription.add(vt(...Fs.map(e=>St(this.element,e)),St(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Qe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(St(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(St(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Vt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Kr(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Qe.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){at(this.element),at(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),Vt(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var Yi=class{constructor(e,t){this.fov=e,this.orientation=t}};var ji=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,a=t-this.camera.orientation.y,s=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:a,z:s},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 Us=`attribute vec2 a_vertex;
|
|
38
|
+
attribute vec2 a_texel;
|
|
39
|
+
|
|
40
|
+
varying vec2 v_texel;
|
|
41
|
+
|
|
42
|
+
void main(void) {
|
|
43
|
+
// direct vertex drawing
|
|
44
|
+
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
45
|
+
// save texel vector to pass to fragment shader
|
|
46
|
+
v_texel = a_texel;
|
|
47
|
+
}
|
|
48
|
+
`;var Hs=`#ifdef GL_ES
|
|
49
|
+
precision highp float;
|
|
50
|
+
precision highp int;
|
|
40
51
|
#else
|
|
41
|
-
precision highp float;
|
|
42
|
-
#define GLSLIFY 1
|
|
52
|
+
precision highp float;
|
|
43
53
|
#endif
|
|
54
|
+
|
|
44
55
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class gr{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new lr(this.params.fov,this.params.orientation),this.cameraRotationManager=new fr(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),r=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(r,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(pr,this.gl.VERTEX_SHADER),i=this.createShader(mr,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,r=e-i,n=t-s,o=e+i,d=t-s,c=e+i,u=t+s,h=e-i,p=t+s;return[r,n,o,d,c,u,h,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class fs{scene3D;subscription=new ee;videoState=new ne(se.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new it;droppedFramesManager=new rs;videoTracks$=new g([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Ks;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=mt(this.video),s=this.constructor.name,r=o=>{e.error$.next({id:s,category:P.WTF,message:`${s} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:(o,d)=>this.subscription.add(o.subscribe(d,r))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:r}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(T(c=>c.map(({track:u})=>u)))}),r(i.ended$,e.endedEvent$),r(i.looped$,e.loopedEvent$),r(i.error$,e.error$),r(i.isBuffering$,e.isBuffering$),r(i.currentBuffer$,e.currentBuffer$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.isLive$,e.isLive$),r(this.player.lastRequestFirstBytes$.pipe(oe(A),Se()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Vt(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,s)),r(ws(this.video),this.elementSize$),r(Dt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),R(t.playbackState,l.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),R(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===De.MANIFEST_READY){const u=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();v(h,"Manifest not loaded or empty");const p=Array.from(h.audio).sort((y,$)=>$.bitrate-y.bitrate),f=Array.from(h.video).sort((y,$)=>$.bitrate-y.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const y of p){const $=Za(y);$&&this.audioTracks.push({track:$,representation:y})}for(const y of f){const $=Ka(y);if($){u.push({track:$,representation:y});const _=!this.params.tuning.isAudioDisabled&&er(p,f,y);_&&this.audioRepresentations.set(y.id,_)}}this.videoTracks$.next(u);for(const y of S){const $=tr(y);$&&this.textTracks.push({track:$,representation:y})}this.params.output.availableVideoTracks$.next(u.map(({track:y})=>y)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:y})=>y)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:y})=>y));const w=this.selectVideoRepresentation();v(w),this.player.initRepresentations(w.id,this.audioRepresentations.get(w.id)?.id,this.params.sourceHls)}else c===De.REPRESENTATIOS_READY&&(this.videoState.setState(se.READY),this.player.initBuffer())},s));const n=c=>e.error$.next({id:"RepresentationSwitch",category:P.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),u=this.player.state$.getTransition();if(c!==De.RUNNING||u||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),S=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let w=h.id;!this.params.output.elementVisible$.getValue()&&f&&(w=this.videoTracks$.getValue().map($=>$.representation).sort(($,_)=>_.bitrate-$.bitrate).filter($=>{const _=dt($),M=dt(h);if(_&&M)return Kt(_,M)&&Kt(_,S)}).map($=>$.id)[0]),this.player.switchRepresentation(me.VIDEO,w).catch(n);const y=this.audioRepresentations.get(h.id);y&&this.player.switchRepresentation(me.AUDIO,y.id).catch(n)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(de(),T(c=>c&&this.videoTracks$.getValue().find(({representation:{id:u}})=>u===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(u){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${u}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,s)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,s)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(T(({to:c})=>c===l.READY),de());this.subscription.add(O(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===l.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(O(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const d=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:h}})=>h===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),r=Mt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(r/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=ri(this.videoTracks$.getValue().map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:o,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),u=e?c??i:i??c;return u&&this.videoTracks$.getValue().find(({track:h})=>h===u)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===G.Requested&&i?.to!==l.PAUSED&&e!==se.STOPPED&&t!==l.STOPPED){const n=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-n,s.forcePrecise)}if(t===l.STOPPED){e!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}switch(e){case se.STOPPED:this.videoState.startTransitionTo(se.READY),this.prepare();return;case se.READY:t===l.PAUSED?(this.videoState.setState(se.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):i?.to===l.READY&&R(this.params.desiredState.playbackState,l.READY);return;case se.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case se.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;default:return V(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){gt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(se.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ft(this.video)}}class Sr extends fs{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class br extends fs{constructor(e){super(e),this.liveOffset=new Pi}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Le({interval:Bt(Et),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===se.PLAYING&&!this.player.isActiveLowLatency){const r=e.position$.getValue()+(s-1);e.position$.next(r),this.liveOffset?.resetTo(-r*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(T(({liveBufferTime:s,liveAvailabilityStartTime:r})=>s&&r?s+r:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===l.PAUSED&&i===se.PAUSED,r=-e,n=Math.trunc(r/1e3<=Math.abs(this.params.output.duration$.getValue())?r:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,s)})}}const _e={};var z;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const Tt=(a,e)=>new ki(t=>{const i=(s,r)=>t.next(r);return a.on(e,i),()=>a.off(e,i)});class yr{subscription=new ee;videoState=new ne(z.INITIALIZING);video;params;hls;textTracksManager=new it;trackLevels=new Map;constructor(e){this.video=lt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(qe(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ft(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:P.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(_e.Hls=s.default,_e.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){v(_e.Hls,"hls.js not loaded"),this.hls=new _e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){v(_e.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:P.WTF,message:"HlsJsProvider internal logic error",thrown:c})},s=mt(this.video),r=(c,u)=>this.subscription.add(c.subscribe(u,i));r(s.timeUpdate$,t.position$),r(s.durationChange$,t.duration$),r(s.ended$,t.endedEvent$),r(s.looped$,t.loopedEvent$),r(s.error$,t.error$),r(s.isBuffering$,t.isBuffering$),r(s.currentBuffer$,t.currentBuffer$),r(s.loadStart$,t.firstBytesEvent$),r(s.playing$,t.firstFrameEvent$),r(s.canplay$,t.canplay$),r(s.seeked$,t.seekedEvent$),r(s.inPiP$,t.inPiP$),r(s.inFullscreen$,t.inFullscreen$),this.subscription.add(Vt(this.video,e.isLooped,i)),this.subscription.add(pt(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pt(this.video,e.playbackRate,s.playbackRateState$,i)),r(Dt(this.video),t.elementVisible$),this.subscription.add(Tt(this.hls,_e.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:P.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),R(e.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),R(e.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i)),r(Tt(this.hls,_e.Events.MANIFEST_PARSED).pipe(T(({levels:c})=>c.reduce((u,h)=>{const p=h.name||h.height.toString(10),{width:f,height:S}=h,w=ai(h.attrs.QUALITY??"")??dt({width:f,height:S});if(!w)return u;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,$={id:p.toString(),quality:w,bitrate:h.bitrate/1e3,size:{width:f,height:S},fps:y};return this.trackLevels.set(p,{track:$,level:h}),u.push($),u},[]))),t.availableVideoTracks$),r(Tt(this.hls,_e.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){const u=[];for(const h of c.subtitleTracks){const p=h.name,f=h.attrs.URI||"",S=h.lang,w="internal";u.push({id:p,url:f,language:S,type:w})}e.internalTextTracks.startTransitionTo(u)}}),r(Tt(this.hls,_e.Events.LEVEL_LOADING).pipe(T(({url:c})=>qe(c))),t.hostname$),r(Tt(this.hls,_e.Events.FRAG_CHANGED),c=>{const{video:u,audio:h}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((u?.endPTS??0)-(u?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((h?.endPTS??0)-(h?.startPTS??0))*1e3)}),this.subscription.add(Qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));const n=c=>Array.from(this.trackLevels.values()).find(({level:u})=>u===c)?.track,o=Tt(this.hls,_e.Events.LEVEL_SWITCHED).pipe(T(({level:c})=>n(this.hls.levels[c])));o.pipe(oe(A)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Qe(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{if(Q(c))return;const u=this.trackLevels.get(c.id)?.level;if(!u)return;const h=this.hls.levels.indexOf(u),p=this.hls.currentLevel,f=this.hls.levels[p];!f||u.bitrate>f.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:i})),r(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==z.INITIALIZING)switch(i?.to!==l.PAUSED&&s.state===G.Requested&&this.seek(s.position),t){case l.STOPPED:switch(e){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:V(e)}break;case l.READY:switch(e){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:V(e)}break;case l.PLAYING:switch(e){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:V(e)}break;case l.PAUSED:switch(e){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED);break;case z.PLAYING:this.pause();break;default:V(e)}break;default:V(t)}};prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(z.PLAYING),await gt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:t}))||(this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(z.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0)}}const Gi="X-Playback-Duration";var qi=async a=>{const e=await fetch(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Gi)?parseInt(e.headers.get(Gi),10):void 0};const Tr=a=>{let e=null;if(a.QUALITY&&(e=ai(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=dt({width:t,height:i})}return e??null},vr=(a,e)=>{const t=a.split(`
|
|
46
|
-
`),i=[],s=[];for(let r=0;r<t.length;r++){const n=t[r],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),d=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!d)){if(o){const c=Object.fromEntries(o[1].split(",").map(y=>y.split("="))),u=c.QUALITY??`stream-${c.BANDWIDTH}`,h=Tr(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const f=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let S;if(c.RESOLUTION){const[y,$]=c.RESOLUTION.split("x").map(_=>parseInt(_,10));y&&$&&(S={width:y,height:$})}const w=new URL(t[++r],e).toString();h&&i.push({id:u,quality:h,url:w,bandwidth:p,size:S,fps:f})}if(d){const c=Object.fromEntries(d[1].split(",").map(f=>f.split("=")).map(([f,S])=>[f,S.replace(/^"|"$/g,"")])),u=c.URI?.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,p=c.NAME;u&&h&&s.push({type:"internal",id:h,label:p,language:h,url:u,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:s}},Er=a=>new Promise(e=>{setTimeout(()=>{e()},a)});let pi=0;const Ci=async(a,e=a,t)=>{const s=await(await fetch(a)).text();pi+=1;try{const{qualityManifests:r,textTracks:n}=vr(s,e);return{qualityManifests:r,textTracks:n}}catch{if(pi<=t.manifestRetryMaxCount)return await Er(jt(pi-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ci(a,e,t)}return{qualityManifests:[],textTracks:[]}};var K;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(K||(K={}));class Ar{subscription=new ee;videoState=new ne(K.STOPPED);video;params;textTracksManager=new it;masterManifest;manifests$=new g([]);maxSeekBackTime$;liveOffset=new Pi;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ke.INVARIANT,url:this.params.source.url},Ci(Oe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:P.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:P.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(qe(this.params.source.url)),this.maxSeekBackTime$=new g(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:P.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},s=mt(this.video),r=(o,d)=>this.subscription.add(o.subscribe(d,i));r(s.ended$,e.endedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,s.playbackRateState$,i)),r(Dt(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),R(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),R(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(de(),T(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&A(c.to)){const h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(qe(p.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),d&&d.from===K.CHANGING_MANIFEST&&this.videoState.setState(d.to),o&&o.state===G.Requested&&this.seek(o.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Le({startTime:this.manifestStartTime$.pipe(oe(A)),currentTime:s.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),i)),this.subscription.add(this.manifests$.pipe(T(o=>o.map(({id:d,quality:c,size:u,bandwidth:h,fps:p})=>({id:d,quality:c,size:u,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ft(this.video)}prepare(){const e=this.selectManifest();if(Q(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:o,min:d}=t?.to??i??{};for(const[c,u]of[[o,"mq"],[d,"lq"]]){const h=String(parseFloat(c||""));u&&c&&s.searchParams.set(u,h)}}const r=this.params.format===m.HLS_LIVE_CMAF?le.DASH_CMAF_OFFSET_P:le.OFFSET_P,n=Oe(s.toString(),this.liveOffset.getTotalOffset(),r);this.video.setAttribute("src",n),this.video.load(),qi(n).then(o=>{if(!Q(o))this.maxSeekBackTime$.next(o);else{const d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Q(d)||!isFinite(d))try{fetch(n).then(c=>c.text()).then(c=>{const u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(u){const h=new URL(u,n).toString();qi(h).then(p=>{Q(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===l.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(r||n||o){const u=this.videoState.getState();this.videoState.setState(K.CHANGING_MANIFEST),this.videoState.startTransitionTo(u),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state===G.None&&this.params.desiredState.seekState.setState({state:G.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&c.state===G.Requested){this.videoState.startTransitionTo(K.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case K.READY:i===l.READY?R(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(K.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case K.PAUSED:if(i===l.PLAYING)if(this.videoState.startTransitionTo(K.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.prepare()}else s?.to===l.PAUSED&&(R(this.params.desiredState.playbackState,l.PAUSED),this.liveOffset.pause());return;case K.CHANGING_MANIFEST:break;default:return V(t)}}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(te||(te={}));class $r{subscription=new ee;videoState=new ne(te.STOPPED);video;params;textTracksManager=new it;masterManifest;manifests$=new g([]);constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ke.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ci(Oe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:P.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),r=s?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;const o=i?"master":r;return i&&!s&&t.startTransitionTo(this.masterManifest),n.find(d=>d.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:P.WTF,message:"HlsProvider internal logic error",thrown:o})},s=mt(this.video),r=(o,d)=>this.subscription.add(o.subscribe(d));if(r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Vt(this.video,t.isLooped,i)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),R(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),R(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&A(c.to)){const h=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(qe(p.url));const f=this.params.desiredState.playbackRate.getState(),S=this.params.output.element$.getValue()?.playbackRate;if(f!==S){const w=this.params.output.element$.getValue();w&&(this.params.desiredState.playbackRate.setState(f),w.playbackRate=f)}}}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),d&&d.from===te.CHANGING_MANIFEST&&this.videoState.setState(d.to),o.state===G.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(T(o=>o.map(({id:d,quality:c,size:u,bandwidth:h,fps:p})=>({id:d,quality:c,size:u,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!Ps()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(O(C(o,"addtrack"),C(o,"removetrack"),C(o,"change"),Ce(["init"])).subscribe(()=>{for(let d=0;d<o.length;d++)o[d].mode="hidden"},i))}const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ft(this.video)}prepare(){const e=this.selectManifest();if(Q(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:r,min:n}=t?.to??i??{};for(const[o,d]of[[r,"mq"],[n,"lq"]]){const c=String(parseFloat(o||""));d&&o&&s.searchParams.set(d,c)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===l.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(te.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(r||n||o){const u=this.videoState.getState();this.videoState.setState(te.CHANGING_MANIFEST),this.videoState.startTransitionTo(u);const{currentTime:h}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state===G.None&&this.params.desiredState.seekState.setState({state:G.Requested,position:h*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&c.state===G.Requested&&this.seek(c.position),t){case te.READY:i===l.READY?R(this.params.desiredState.playbackState,l.READY):i===l.PAUSED?(this.videoState.setState(te.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):i===l.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:i===l.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):s?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case te.PAUSED:i===l.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;case te.CHANGING_MANIFEST:break;default:return V(t)}}}var re;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(re||(re={}));class kr{subscription=new ee;videoState=new ne(re.STOPPED);video;trackUrls={};params;textTracksManager=new it;constructor(e){this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const r=s.toString(10);this.trackUrls[r]={track:{quality:t,id:r},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:P.WTF,message:"MpegProvider internal logic error",thrown:o})},s=mt(this.video),r=(o,d)=>this.subscription.add(o.subscribe(d,i));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.loadedMetadata$,e.firstBytesEvent$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.seeked$,e.seekedEvent$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),this.subscription.add(Vt(this.video,t.isLooped,i)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,s.playbackRateState$,i)),r(Dt(this.video),e.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),R(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),R(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===re.READY&&this.videoState.setState(re.READY);const o=this.params.desiredState.videoTrack.getTransition();if(o&&A(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);const d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){const u=this.params.output.element$.getValue();u&&(this.params.desiredState.playbackRate.setState(d),u.playbackRate=d)}}this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ft(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;v(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];v(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(qe(t))}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(r&&e!==re.READY&&!n){this.handleQualityLimitTransition(r.to.max);return}if(e===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){const{currentTime:d}=this.video;this.prepare(),o.state===G.None&&this.params.desiredState.seekState.setState({state:G.Requested,position:d*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==l.PAUSED&&o.state===G.Requested&&this.seek(o.position),e){case re.READY:t===l.READY?R(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):i?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case re.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;default:return V(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(o=>!ut(o.track.quality)&&Kt(o.track.quality,e))?.track,r=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[r??"0"]?.track;if(s&&n&&gi(n.quality,s.quality)&&(t=s),!t){const o=Object.values(this.trackUrls).filter(c=>!ut(c.track.quality)&&$t(c.track.quality,e)),d=o.length;d&&(t=o[d-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(r=>r.track);t=ri(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const zi=["stun:videostun.mycdn.me:80"],wr=1e3,Pr=3,mi=()=>null;class Dr{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=mi;externalStopCallback=mi;externalErrorCallback=mi;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:zi}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:P.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),wr)}normalizeOptions(e={}){const t={stunServerList:zi,maxRetryNumber:Pr,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Z;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Z||(Z={}));class Lr{subscription;params;log;video;videoState=new ne(Z.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new ee,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=lt(e.container),this.liveStreamClient=new Dr(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ft(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:P.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(T(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(T(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const s=mt(this.video),r=(n,o)=>this.subscription.add(n.subscribe(o,i));r(s.timeUpdate$,e.liveTime$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(Dt(this.video),this.params.output.elementVisible$),this.subscription.add(s.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(pt(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case Z.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(l.STOPPED);break;case Z.READY:break;case Z.PAUSED:t.playbackState.setState(l.PAUSED);break;case Z.PLAYING:t.playbackState.setState(l.PLAYING);break;default:return V(n.to)}},i)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ce(["init"])).pipe(Ge(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ke.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,l.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Z.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:P.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){gt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:P.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),R(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(r){this.prepare();return}switch(e){case Z.READY:t===l.PAUSED?(this.videoState.setState(Z.PAUSED),R(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):i?.to===l.PLAYING&&R(this.params.desiredState.playbackState,l.PLAYING);return;case Z.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&R(this.params.desiredState.playbackState,l.PAUSED);return;default:return V(e)}}}class Wi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var ye;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg",a.DASH_ANY_MPEG="dash_any_mpeg",a.DASH_ANY_WEBM="dash_any_webm",a.DASH_SEP="dash_sep"})(ye||(ye={}));var tt;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(tt||(tt={}));const ps=$i().device===Ds.Android,si=document.createElement("video"),xr='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Cr='video/mp4; codecs="hev1.1.6.L93.B0"',ms='video/webm; codecs="vp09.00.10.08"',gs='video/webm; codecs="av01.0.00M.08"',Rr='audio/mp4; codecs="mp4a.40.2"',Ir='audio/webm; codecs="opus"',rt={mms:ls(),mse:dr(),hls:!!(si.canPlayType?.("application/x-mpegurl")||si.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!si.canPlayType?.("video/mp4"),webm:!!si.canPlayType?.("video/webm"),cmaf:!0},Ye={h264:!!at()?.isTypeSupported?.(xr),h265:!!at()?.isTypeSupported?.(Cr),vp9:!!at()?.isTypeSupported?.(ms),av1:!!at()?.isTypeSupported?.(gs),aac:!!at()?.isTypeSupported?.(Rr),opus:!!at()?.isTypeSupported?.(Ir)},It=(Ye.h264||Ye.h265)&&Ye.aac;let nt;const Br=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gs}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:ms}})]);nt={[m.DASH_WEBM_AV1]:e,[m.DASH_WEBM]:t}};try{Br()}catch(a){console.error(a)}const Ft=rt.hls&&Pe.mp4,Mr=()=>Object.keys(Ye).filter(a=>Ye[a]),_r=(a,e=!1,t=!1)=>{const i=rt.mse||rt.mms&&t;return a.filter(s=>{switch(s){case m.DASH_SEP:return i&&Pe.mp4&&It;case m.DASH_WEBM:return i&&Pe.webm&&Ye.vp9&&Ye.opus;case m.DASH_WEBM_AV1:return i&&Pe.webm&&Ye.av1&&Ye.opus;case m.DASH_LIVE:return rt.mse&&Pe.mp4&&It;case m.DASH_LIVE_CMAF:return i&&Pe.mp4&&It&&Pe.cmaf;case m.DASH_ONDEMAND:return i&&Pe.mp4&&It;case m.HLS:case m.HLS_ONDEMAND:return Ft||e&&rt.mse&&Pe.mp4&&It;case m.HLS_LIVE:case m.HLS_LIVE_CMAF:return Ft;case m.MPEG:return Pe.mp4;case m.DASH_LIVE_WEBM:return!1;case m.WEB_RTC_LIVE:return rt.webrtc&&rt.ws&&Ye.h264&&(Pe.mp4||Pe.webm);default:return V(s)}})},et=a=>{const e=m.DASH_WEBM,t=m.DASH_WEBM_AV1;switch(a){case tt.VP9:return[e,t];case tt.AV1:return[t,e];case tt.NONE:return[];case tt.SMOOTH:return nt?nt[t].smooth?[t,e]:nt[e].smooth?[e,t]:[t,e]:[e,t];case tt.POWER_EFFICIENT:return nt?nt[t].powerEfficient?[t,e]:nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:V(a)}return[e,t]},Or=({webmCodec:a,androidPreferredFormat:e})=>{if(ps)switch(e){case ye.MPEG:return[m.MPEG,...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND];case ye.HLS:return[m.HLS,m.HLS_ONDEMAND,...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.MPEG];case ye.DASH:return[...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG];case ye.DASH_ANY_MPEG:return[m.DASH_SEP,m.DASH_ONDEMAND,m.MPEG,...et(a),m.HLS,m.HLS_ONDEMAND];case ye.DASH_ANY_WEBM:return[...et(a),m.MPEG,m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND];case ye.DASH_SEP:return[m.DASH_SEP,m.MPEG,...et(a),m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND];default:V(e)}return Ft?[...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG]:[...et(a),m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG]},Nr=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{const i=e?[m.DASH_LIVE_CMAF,m.DASH_LIVE]:[m.DASH_LIVE,m.DASH_LIVE_CMAF],s=e?[m.HLS_LIVE_CMAF,m.HLS_LIVE]:[m.HLS_LIVE,m.HLS_LIVE_CMAF],r=[...i,...s],n=[...s,...i];let o;if(ps)switch(a){case ye.DASH:case ye.DASH_ANY_MPEG:case ye.DASH_ANY_WEBM:case ye.DASH_SEP:{o=r;break}case ye.HLS:case ye.MPEG:{o=n;break}default:V(a)}else Ft?o=n:o=r;return t?[m.WEB_RTC_LIVE,...o]:[...o,m.WEB_RTC_LIVE]},Qi=a=>a?[m.HLS_LIVE,m.HLS_LIVE_CMAF,m.DASH_LIVE_CMAF]:[m.DASH_WEBM,m.DASH_WEBM_AV1,m.DASH_SEP,m.DASH_ONDEMAND,m.HLS,m.HLS_ONDEMAND,m.MPEG];var Fr=a=>new ki(e=>{const t=new ee,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(T(({from:c,to:u})=>`${c}-${u}`)),s=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$.pipe(T(({type:c})=>c!==void 0)),n=new x;let o=0,d="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),d=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(o),d="unknown",o=0})),t.add(r.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Vr={chunkDuration:5e3,maxParallelRequests:5};class Ur{current$=new g({type:void 0});providerError$=new x;noAvailableProvidersError$=new x;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),currentVideoSegmentLength$:new g(0),currentAudioSegmentLength$:new g(0),availableVideoTracks$:new g([]),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),autoVideoTrackLimitingAvailable$:new g(!1),autoVideoTrackLimits$:new g(void 0),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new g(void 0),isLowLatency$:new g(!1),canChangePlaybackSpeed$:new g(!0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),inPiP$:new g(!1),inFullscreen$:new g(!1),element$:new g(void 0),elementVisible$:new g(!0),availableSources$:new g(void 0),is3DVideo$:new g(!1)};subscription=new ee;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=_r([...Nr(this.params.tuning),...Or(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>A(e.sources[o])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let r=[];i?r=[i]:s.length?r=[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:r=t,this.log({message:`Selected formats: ${r.join(" > ")}`}),this.screenFormatsIterator=new Wi(r);const n=[...Qi(!0),...Qi(!1)];this.chromecastFormatsIterator=new Wi(n.filter(o=>A(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(Q(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:P.WTF,message:"Failed to create provider",thrown:s})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),s=i.state!==G.None;if(this.params.desiredState.seekState.setState({state:G.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ge.SCREEN:return this.createScreenProvider(t);case ge.CHROMECAST:return this.createChromecastProvider(t);default:return V(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,r=this.providerOutput,n={container:i,source:null,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case m.DASH_SEP:case m.DASH_WEBM:case m.DASH_WEBM_AV1:case m.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t[m.HLS_ONDEMAND]||t[m.HLS]);return v(o),new Sr({...n,source:o,sourceHls:d})}case m.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return v(o),new br({...n,source:o})}case m.HLS:case m.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return v(o),Ft||!this.params.tuning.useHlsJs?new $r({...n,source:o}):new yr({...n,source:o})}case m.HLS_LIVE:case m.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return v(o),new Ar({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case m.MPEG:{const o=this.applyFailoverHost(t[e]);return v(o),new kr({...n,source:o})}case m.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return v(o),new fa({...n,source:o,config:{...Vr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case m.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return v(o),new Lr({container:i,source:o,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case m.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return v(o),new Fs({connection:o,meta:r,container:i,source:t,format:e,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ge.CHROMECAST:ge.SCREEN}chooseFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ge.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return V(e)}}skipFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.next();case ge.CHROMECAST:return this.chromecastFormatsIterator.next();default:return V(e)}}handleNoFormatsError(e){switch(e){case ge.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ge.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return V(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const r=new URL(s);return r.host=t,r.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([s,r])=>[s,i(r)]))}initProviderErrorHandling(){const e=new ee;let t=!1,i=0;return e.add(O(this.providerOutput.error$,Fr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(T(s=>({id:`ProviderHangup:${s}`,category:P.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(oe(({to:r})=>r===l.PLAYING),Se()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const r=this.current$.getValue().destination;if(r===ge.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ge.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===P.NETWORK,o=s.category===P.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o;d&&!o&&(n&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(r??ge.SCREEN)}})),e}}const Hr=5e3,ji="one_video_throughput",Ji="one_video_rtt",_t=window.navigator.connection,Xi=()=>{const a=_t?.downlink;if(A(a)&&a!==10)return a*1e3},Ki=()=>{const a=_t?.rtt;if(A(a)&&a!==3e3)return a},Zi=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Ot{throughput;rtt;subscription=new ee;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Ot.load(ji)||(e.useBrowserEstimation?Xi():void 0)||Hr,i=Ot.load(Ji)??(e.useBrowserEstimation?Ki():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(i),this.rttAdjustedThroughput$=new g(Zi(t,i,e.rttPenaltyRequestSize)),this.throughput=Ai.getSmoothedValue(t,-1,e),this.rtt=Ai.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const n=Xi();n&&this.throughput.next(n);const o=Ki();A(o)&&this.rtt.next(o)};_t&&"onchange"in _t&&this.subscription.add(C(_t,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{li.set(ji,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{li.set(Ji,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Le({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(T(({throughput:s,rtt:r})=>Zi(s,r,e.rttPenaltyRequestSize)),oe(s=>{const r=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-r)/r>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ae();const s=new ee;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(C(e,"progress").pipe(Se()).subscribe(r=>{t=r.loaded,i=ae()}));break;case 1:case 0:s.add(C(e,"loadstart").subscribe(()=>{t=0,i=ae()}));break}s.add(C(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=ae(),d=n-t,c=o-i;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,r=ae(),n=0,o=ae();const d=u=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},c=async({done:u,value:h})=>{if(u)!t&&this.addRawSpeed(s,ae()-r,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(ae()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=h.byteLength;else{const f=o-r;f&&this.addRawSpeed(n,f,1,t),n=h.byteLength,r=ae()}o=ae()}else s+=h.byteLength,n+=h.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ae()-o,this.concurrentDownloads.size),n=0,o=ae());await i?.read().then(c,d)}};this.concurrentDownloads.add(e),i?.read().then(c,d)}addRawSpeed(e,t,i=1,s=!1){if(Ot.sanityCheck(e,t,s)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=li.get(e);if(A(t))return parseInt(t,10)??void 0}}const es={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ke.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ke.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:tt.VP9,androidPreferredFormat:ye.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Yr=a=>({...Ls(a,es),configName:[...a.configName??[],...es.configName]});var ts=({seekState:a,position$:e})=>O(a.stateChangeEnded$.pipe(T(({to:t})=>t.state===G.None?void 0:(t.position??NaN)/1e3),oe(A)),e.pipe(oe(()=>a.getState().state===G.None))),Gr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return v(e,`Wrong container or containerId {${a.container}}`),e};const qr=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(oe(s=>s.length>0),Se()).subscribe(s=>{s.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class jr{subscription=new ee;domContainer;providerContainer;chromecastInitializer;logger=new xs;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;hasLiveOffsetByPaused=new g(!1);hasLiveOffsetByPausedTimer=0;desiredState={playbackState:new ne(l.STOPPED),seekState:new ne({state:G.None}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),internalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({}),cameraOrientation:new ne({x:0,y:0})};info={playbackState$:new g(l.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),currentQuality$:new g(void 0),isAutoQualityEnabled$:new g(!0),autoQualityLimitingAvailable$:new g(!1),autoQualityLimits$:new g({}),currentPlaybackRate$:new g(1),currentBuffer$:new g({start:0,end:0}),isBuffering$:new g(!0),isStalled$:new g(!1),isEnded$:new g(!1),isLooped$:new g(!1),isLive$:new g(void 0),canChangePlaybackSpeed$:new g(void 0),atLiveEdge$:new g(void 0),atLiveDurationEdge$:new g(void 0),liveTime$:new g(void 0),liveBufferTime$:new g(void 0),currentFormat$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),throughputEstimation$:new g(void 0),rttEstimation$:new g(void 0),videoBitrate$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),surface$:new g(We.NONE),chromecastState$:new g(pe.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0),availableSources$:new g(void 0),is3DVideo$:new g(!1),currentVideoSegmentLength$:new g(0),currentAudioSegmentLength$:new g(0)};events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x};experimental={element$:new g(void 0),tuningConfigName$:new g([]),enableDebugTelemetry$:new g(!1),dumpTelemetry:js};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Yr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ot(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const r=Reflect.get(t,i,s);return typeof r!="function"?r:(...n)=>{try{return r.apply(t,n)}catch(o){const d=n.map(h=>JSON.stringify(h,(p,f)=>{const S=typeof f;return["number","string","boolean"].includes(S)?f:f===null?null:`<${S}>`})),c=`Player.${String(i)}`,u=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:P.WTF,message:u,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Gr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ur({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===l.STOPPED&&e.startTransitionTo(l.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==l.PLAYING&&t.startTransitionTo(l.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!yi()?C(document,"visibilitychange").pipe(Se()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==l.PAUSED&&e.startTransitionTo(l.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==l.STOPPED&&e.startTransitionTo(l.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:G.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===pe.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===pe.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){v(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),Se()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){v(this.providerContainer);const t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return qr(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const s=i.getCameraRotation(),r=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+r.x,y:s.y+r.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(Q(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===G.None?void 0:t.position;return A(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(T(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(T(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e===l.STOPPED),Se()).subscribe(()=>{this.initedAt=ae(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case l.READY:this.events.ready$.next();break;case l.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case l.PAUSED:this.events.paused$.next();break;case l.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case l.PAUSED:this.events.willPause$.next();break;case l.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case l.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===G.Requested?this.desiredState.seekState.setState({...n,state:G.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:P.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===G.Applying&&(this.desiredState.seekState.setState({state:G.None}),this.events.seeked$.next())})).add(e.current$.pipe(T(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(T(n=>n.destination),de()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(T(n=>n.map(({quality:o})=>o).sort((o,d)=>ut(o)?1:ut(d)?-1:$t(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const d of n)d.fps&&(o[d.quality]=d.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(de()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(de()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(de()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(T(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Le({hasLiveOffsetByPaused:O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(T(n=>n.to),de(),T(n=>n===l.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Le({atLiveEdge:Le({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ts({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(T(({isLive:n,position:o,isLowLatency:d})=>{const c=this.getActiveLiveDelay(d);return n&&Math.abs(o)<c/1e3}),de(),Nt(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(T(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Le({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(T(({isLive:n,position:o,duration:d})=>n&&(Math.abs(d)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),de(),Nt(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(T(n=>n.muted),de()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(T(n=>n.volume),de()).subscribe(this.info.volume$)).add(ts({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(Xt(!0)),e.providerOutput.seekedEvent$.pipe(Xt(!1))).pipe(de()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(T(n=>({id:n?`No${n}`:"NoProviders",category:P.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Se(),T(n=>n??ae()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Se(),T(()=>ae()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Se(),T(()=>ae()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new g(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(oe(({to:n})=>n===l.PLAYING),Se()).subscribe(()=>i.next(!1)));let s=0;const r=O(e.providerOutput.isBuffering$,t,i).pipe(T(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),de());this.subscription.add(r.subscribe(n=>{n?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(O(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(O(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),u=this.chromecastInitializer.castState$.getValue();let h;u===pe.CONNECTED?h=We.SECOND_SCREEN:d?c?n?h=We.PIP:o?h=We.FULLSCREEN:h=We.INLINE:h=We.INVISIBLE:h=We.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(T(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ee;this.subscription.add(t),this.subscription.add(e.current$.pipe(de((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),Se()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=ri(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(T(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(T(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(T(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;v(this.providerContainer),v(e),Qs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ws(t)),this.providerContainer.current$.subscribe(({type:t})=>zt("provider",t)),e.duration$.subscribe(t=>zt("duration",t)),e.availableVideoTracks$.pipe(oe(t=>!!t.length),Se()).subscribe(t=>zt("tracks",t)),this.events.fatalError$.subscribe(new Ue("fatalError")),this.events.managedError$.subscribe(new Ue("managedError")),e.position$.subscribe(new Ue("position")),e.currentVideoTrack$.pipe(T(t=>t?.quality)).subscribe(new Ue("quality")),this.info.currentBuffer$.subscribe(new Ue("buffer")),e.isBuffering$.subscribe(new Ue("isBuffering"))].forEach(t=>this.subscription.add(t)),zt("codecs",Mr())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:P.DOM,message:String(s)})})};this.subscription.add(O(C(document,"visibilitychange"),C(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",r=this.desiredState.playbackState.getState()===l.PLAYING,n=!!e&&!e?.released;s&&r?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const Jr=`@vkontakte/videoplayer-core@${Cs}`;export{pe as ChromecastState,Si as HttpConnectionType,Zr as Observable,l as PlaybackState,jr as Player,Jr as SDK_VERSION,en as Subject,tn as Subscription,We as Surface,Cs as VERSION,sn as ValueSubject,m as VideoFormat,an as VideoQuality};
|
|
56
|
+
|
|
57
|
+
varying vec2 v_texel; // [0..1, 0..1]
|
|
58
|
+
|
|
59
|
+
uniform sampler2D u_texture;
|
|
60
|
+
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
61
|
+
|
|
62
|
+
void main(void) {
|
|
63
|
+
// center point of output projection
|
|
64
|
+
float lambda0 = u_focus.x / 360.0;
|
|
65
|
+
float phi0 = u_focus.y / 180.0;
|
|
66
|
+
|
|
67
|
+
float lambda = PI * 2.0 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
68
|
+
float phi = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
69
|
+
|
|
70
|
+
float p = sqrt(lambda * lambda + phi * phi); // rou
|
|
71
|
+
float c = atan(p);
|
|
72
|
+
float cos_c = cos(c);
|
|
73
|
+
float sin_c = sin(c);
|
|
74
|
+
|
|
75
|
+
// geo coordinates of projection
|
|
76
|
+
float x = lambda0 + atan(
|
|
77
|
+
lambda * sin_c,
|
|
78
|
+
p * cos(phi0) * cos_c - phi * sin(phi0) * sin_c
|
|
79
|
+
);
|
|
80
|
+
float y = asin(cos_c * sin(phi0) + (phi * sin_c * cos(phi0)) / p);
|
|
81
|
+
|
|
82
|
+
// reprojected texture coordinates
|
|
83
|
+
vec2 tc = vec2(
|
|
84
|
+
mod(x / (PI * 2.0) - 0.5, 1.0), // [0..1]
|
|
85
|
+
mod(y / PI - 0.5, 1.0) // [0..1]
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
// sample using new coordinates
|
|
89
|
+
gl_FragColor = texture2D(u_texture, tc);
|
|
90
|
+
}
|
|
91
|
+
`;var qi=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 Yi(this.params.fov,this.params.orientation),this.cameraRotationManager=new ji(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"),a=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(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(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(Us,this.gl.VERTEX_SHADER),i=this.createShader(Hs,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,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,s,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var nt=class{constructor(e){this.subscription=new qd;this.videoState=new $("stopped");this.elementSize$=new js(void 0);this.textTracksManager=new oe;this.droppedFramesManager=new Oi;this.videoTracks$=new js([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Mi;this.textTracks=[];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"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(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"),v(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&v(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Fd(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new qi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=q(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Wi({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=J(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Xr.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(Zr(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Hd(Gd),jd()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Te(this.video,t.isLooped,r)),this.subscription.add(K(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ne(this.video,t.playbackRate,i.playbackRateState$,r)),a(Yd(this.video),this.elementSize$),a(ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){let l=[];this.audioTracks=[],this.textTracks=[];let c=this.player.getRepresentations();Qs(c,"Manifest not loaded or empty");let h=Array.from(c.audio).sort((f,S)=>S.bitrate-f.bitrate),p=Array.from(c.video).sort((f,S)=>S.bitrate-f.bitrate),m=Array.from(c.text);if(!this.params.tuning.isAudioDisabled)for(let f of h){let S=xs(f);S&&this.audioTracks.push({track:S,representation:f})}for(let f of p){let S=Es(f);if(S){l.push({track:S,representation:f});let b=!this.params.tuning.isAudioDisabled&&ks(h,p,f);b&&this.audioRepresentations.set(f.id,b)}}this.videoTracks$.next(l);for(let f of m){let S=Ps(f);S&&this.textTracks.push({track:S,representation:f})}this.params.output.availableVideoTracks$.next(l.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:f})=>f));let y=this.selectVideoRepresentation();Qs(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id,this.params.sourceHls)}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:Xr.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(zi(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Qd(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="running"||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);let p=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let y=c.id;!this.params.output.elementVisible$.getValue()&&p&&(y=this.videoTracks$.getValue().map(S=>S.representation).sort((S,b)=>b.bitrate-S.bitrate).filter(S=>{let b=Ys(S),P=Ys(c);if(b&&P)return Ws(b,P)&&Ws(b,m)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",y).catch(s);let f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation("audio",f.id).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Gs(),Zr(d=>d&&this.videoTracks$.getValue().find(({representation:{id:l}})=>l===d)?.track)).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}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(Zr(({to:d})=>d==="ready"),Gs());this.subscription.add(zi(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(zi(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=zi(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Wd(["init"])).pipe(Ud(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:c}})=>c===t)?.track,r=this.params.output.currentVideoTrack$.getValue(),a=Ue(this.video.buffered,this.video.currentTime*1e3),s=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(s,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,r?this.audioRepresentations.get(r.id)?.bitrate??0:0),d=Fe(this.videoTracks$.getValue().map(({track:c})=>c),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),l=e?d??i:i??d;return l&&this.videoTracks$.getValue().find(({track:c})=>c===l)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){X(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xr.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),z(this.video)}};var ui=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 qs,interval as zd,map as Kd}from"@vkontakte/videoplayer-shared";var li=class extends nt{constructor(e){super(e),this.liveOffset=new Pe}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(qs({interval:zd(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let a=e.position$.getValue()+(r-1);e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(qs({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Kd(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(s,r)})}};import{assertNever as ci,assertNonNullable as zs,debounce as Jd,ErrorCategory as Ki,filter as Xd,isNonNullable as Zd,isNullable as eu,map as ea,merge as tu,Observable as iu,observableFrom as ru,Subscription as au,videoSizeToQuality as su}from"@vkontakte/videoplayer-shared";var ge={};var yt=(n,e)=>new iu(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),pi=class{constructor(e){this.subscription=new au;this.videoState=new $("initializing");this.textTracksManager=new oe;this.trackLevels=new Map;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(e!=="initializing")switch(i?.to!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ci(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ci(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ci(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ci(e)}break;default:ci(t)}};this.video=q(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Q(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),z(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ki.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(ge.Hls=r.default,ge.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){zs(ge.Hls,"hls.js not loaded"),this.hls=new ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){zs(ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:Ki.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=J(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Te(this.video,e.isLooped,i)),this.subscription.add(K(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ne(this.video,e.playbackRate,r.playbackRateState$,i)),a(ue(this.video),t.elementVisible$),this.subscription.add(yt(this.hls,ge.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:Ki.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(yt(this.hls,ge.Events.MANIFEST_PARSED).pipe(ea(({levels:d})=>d.reduce((l,c)=>{let h=c.name||c.height.toString(10),{width:p,height:m}=c,y=_e(c.attrs.QUALITY??"")??su({width:p,height:m});if(!y)return l;let f=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:y,bitrate:c.bitrate/1e3,size:{width:p,height:m},fps:f};return this.trackLevels.set(h,{track:S,level:c}),l.push(S),l},[]))),t.availableVideoTracks$),a(yt(this.hls,ge.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let h=c.name,p=c.attrs.URI||"",m=c.lang,y="internal";l.push({id:h,url:p,language:m,type:y})}e.internalTextTracks.startTransitionTo(l)}}),a(yt(this.hls,ge.Events.LEVEL_LOADING).pipe(ea(({url:d})=>Q(d))),t.hostname$),a(yt(this.hls,ge.Events.FRAG_CHANGED),d=>{let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(Be(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>Array.from(this.trackLevels.values()).find(({level:l})=>l===d)?.track,o=yt(this.hls,ge.Events.LEVEL_SWITCHED).pipe(ea(({level:d})=>s(this.hls.levels[d])));o.pipe(Xd(Zd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Be(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{if(eu(d))return;let l=this.trackLevels.get(d.id)?.level;if(!l)return;let c=this.hls.levels.indexOf(l),h=this.hls.currentLevel,p=this.hls.levels[h];!p||l.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=tu(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ru(["init"])).pipe(Jd(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await X(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ki.DOM,thrown:t}))||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0)}};var Ks="X-Playback-Duration",ta=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(Ks)?parseInt(e.headers.get(Ks),10):void 0};import{assertNever as cu,combine as pu,debounce as hu,ErrorCategory as Xi,filter as mu,filterChanged as fu,isNonNullable as Xs,isNullable as Zi,map as Zs,merge as bu,observableFrom as gu,Subscription as Su,ValueSubject as ra,VideoQuality as vu}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as nu,getExponentialDelay as ou}from"@vkontakte/videoplayer-shared";var du=n=>{let e=null;if(n.QUALITY&&(e=_e(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=nu({width:t,height:i})}return e??null},uu=(n,e)=>{let t=n.split(`
|
|
92
|
+
`),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let d=Object.fromEntries(o[1].split(",").map(f=>f.split("="))),l=d.QUALITY??`stream-${d.BANDWIDTH}`,c=du(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,m;if(d.RESOLUTION){let[f,S]=d.RESOLUTION.split("x").map(b=>parseInt(b,10));f&&S&&(m={width:f,height:S})}let y=new URL(t[++a],e).toString();c&&i.push({id:l,quality:c,url:y,bandwidth:h,size:m,fps:p})}if(u){let d=Object.fromEntries(u[1].split(",").map(p=>p.split("=")).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),l=d.URI?.replace(/playlist$/,"subtitles.vtt"),c=d.LANGUAGE,h=d.NAME;l&&c&&r.push({type:"internal",id:c,label:h,language:c,url:l,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},lu=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),ia=0,Js=async(n,e=n,t)=>{let r=await(await fetch(n)).text();ia+=1;try{let{qualityManifests:a,textTracks:s}=uu(r,e);return{qualityManifests:a,textTracks:s}}catch{if(ia<=t.manifestRetryMaxCount)return await lu(ou(ia-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Js(n,e,t)}return{qualityManifests:[],textTracks:[]}},Ji=Js;var hi=class{constructor(e){this.subscription=new Su;this.videoState=new $("stopped");this.textTracksManager=new oe;this.manifests$=new ra([]);this.liveOffset=new Pe;this.manifestStartTime$=new ra(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(),a=this.params.desiredState.videoTrack.getTransition(),s=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"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),v(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.pause()):r?.to==="playing"&&v(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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else r?.to==="paused"&&(v(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return cu(t)}};this.params=e,this.video=q(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:vu.INVARIANT,url:this.params.source.url},Ji(Y(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Xi.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xi.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Q(this.params.source.url)),this.maxSeekBackTime$=new ra(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Xi.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=J(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(K(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ne(this.video,t.playbackRate,r.playbackRateState$,i)),a(ue(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(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.subscription.add(this.maxSeekBackTime$.pipe(fu(),Zs(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(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Xs(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Q(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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(pu({startTime:this.manifestStartTime$.pipe(mu(Xs)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Zs(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=bu(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,gu(["init"])).pipe(hu(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),z(this.video)}prepare(){let e=this.selectManifest();if(Zi(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[d,l]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=Y(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),ta(s).then(o=>{if(!Zi(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Zi(u)||!isFinite(u))try{fetch(s).then(d=>d.text()).then(d=>{let l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(l){let c=new URL(l,s).toString();ta(c).then(h=>{Zi(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){X(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xi.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()}};import{assertNever as yu,debounce as Tu,ErrorCategory as aa,fromEvent as sa,isNonNullable as Iu,isNullable as Eu,map as xu,merge as en,observableFrom as tn,Subscription as ku,ValueSubject as Pu,VideoQuality as Au,isIOS as wu}from"@vkontakte/videoplayer-shared";var mi=class{constructor(e){this.subscription=new ku;this.videoState=new $("stopped");this.textTracksManager=new oe;this.manifests$=new Pu([]);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(),a=this.params.desiredState.videoTrack.getTransition(),s=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"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return yu(t)}};this.params=e,this.video=q(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Au.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ji(Y(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:aa.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(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:aa.WTF,message:"HlsProvider internal logic error",thrown:o})},r=J(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Te(this.video,t.isLooped,i)),this.subscription.add(K(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ne(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(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(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Iu(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(p=>p.id===c);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Q(h.url));let p=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(p!==m){let y=this.params.output.element$.getValue();y&&(this.params.desiredState.playbackRate.setState(p),y.playbackRate=p)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(xu(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!wu()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(en(sa(o,"addtrack"),sa(o,"removetrack"),sa(o,"change"),tn(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=en(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,tn(["init"])).pipe(Tu(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),z(this.video)}prepare(){let e=this.selectManifest();if(Eu(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:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let d=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){X(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:aa.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as $u,assertNonNullable as rn,debounce as Lu,ErrorCategory as an,isHigher as Ru,isHigherOrEqual as Du,isInvariantQuality as sn,isLowerOrEqual as Mu,isNonNullable as Cu,merge as Bu,observableFrom as Vu,Subscription as Ou}from"@vkontakte/videoplayer-shared";var fi=class{constructor(e){this.subscription=new Ou;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new oe;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"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?v(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return $u(e)}};this.params=e,this.video=q(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},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:an.WTF,message:"MpegProvider internal logic error",thrown:o})},r=J(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Te(this.video,t.isLooped,i)),this.subscription.add(K(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ne(this.video,t.playbackRate,r.playbackRateState$,i)),a(ue(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(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&&Cu(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(),d=this.params.output.element$.getValue()?.playbackRate;if(u!==d){let l=this.params.output.element$.getValue();l&&(this.params.desiredState.playbackRate.setState(u),l.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Bu(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Vu(["init"])).pipe(Lu(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),z(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;rn(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];rn(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Q(t))}playIfAllowed(){X(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!sn(o.track.quality)&&Mu(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&Du(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(d=>!sn(d.track.quality)&&Ru(d.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=Fe(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as on,debounce as Uu,merge as dn,observableFrom as Hu,Subscription as Qu,map as un,ValueSubject as Gu,ErrorCategory as oa,VideoQuality as Wu}from"@vkontakte/videoplayer-shared";import{ErrorCategory as _u}from"@vkontakte/videoplayer-shared";var nn=["stun:videostun.mycdn.me:80"],Nu=1e3,Fu=3,na=()=>null,er=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=na;this.externalStopCallback=na;this.externalErrorCallback=na;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:nn}]};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:_u.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),Nu)}normalizeOptions(e={}){let t={stunServerList:nn,maxRetryNumber:Fu,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var bi=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new Gu(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"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return on(e)}};this.subscription=new Qu,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=q(e.container),this.liveStreamClient=new er(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),z(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:oa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};dn(this.videoState.stateChangeStarted$.pipe(un(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(un(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=J(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ue(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).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(K(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.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 on(s.to)}},i)).add(dn(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Hu(["init"])).pipe(Uu(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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Wu.INVARIANT}),this.video.srcObject=e,v(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:oa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){X(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var gi=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 vi,assertNonNullable as We,ErrorCategory as rr,filter as al,isNonNullable as vn,isNullable as sl,map as nl,merge as ol,once as dl,Subject as Se,Subscription as yn,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{assertNever as ir,CurrentClientDevice as qu,getCurrentBrowser as zu}from"@vkontakte/videoplayer-shared";var ln=zu().device===qu.Android,tr=document.createElement("video"),Ku='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ju='video/mp4; codecs="hev1.1.6.L93.B0"',cn='video/webm; codecs="vp09.00.10.08"',pn='video/webm; codecs="av01.0.00M.08"',Xu='audio/mp4; codecs="mp4a.40.2"',Zu='audio/webm; codecs="opus"',ot={mms:Qi(),mse:Cs(),hls:!!(tr.canPlayType?.("application/x-mpegurl")||tr.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!tr.canPlayType?.("video/mp4"),webm:!!tr.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!Le()?.isTypeSupported?.(Ku),h265:!!Le()?.isTypeSupported?.(Ju),vp9:!!Le()?.isTypeSupported?.(cn),av1:!!Le()?.isTypeSupported?.(pn),aac:!!Le()?.isTypeSupported?.(Xu),opus:!!Le()?.isTypeSupported?.(Zu)},Si=(Ee.h264||Ee.h265)&&Ee.aac,dt,el=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:pn}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:cn}})]);dt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{el()}catch(n){console.error(n)}var Tt=ot.hls&&le.mp4,hn=()=>Object.keys(Ee).filter(n=>Ee[n]),mn=(n,e=!1,t=!1)=>{let i=ot.mse||ot.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&le.mp4&&Si;case"DASH_WEBM":return i&&le.webm&&Ee.vp9&&Ee.opus;case"DASH_WEBM_AV1":return i&&le.webm&&Ee.av1&&Ee.opus;case"DASH_LIVE":return ot.mse&&le.mp4&&Si;case"DASH_LIVE_CMAF":return i&&le.mp4&&Si&&le.cmaf;case"DASH_ONDEMAND":return i&&le.mp4&&Si;case"HLS":case"HLS_ONDEMAND":return Tt||e&&ot.mse&&le.mp4&&Si;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Tt;case"MPEG":return le.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ot.webrtc&&ot.ws&&Ee.h264&&(le.mp4||le.webm);default:return ir(r)}})},Ge=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return dt?dt[t].smooth?[t,e]:dt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return dt?dt[t].powerEfficient?[t,e]:dt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ir(n)}return[e,t]},fn=({webmCodec:n,androidPreferredFormat:e})=>{if(ln)switch(e){case"mpeg":return["MPEG",...Ge(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...Ge(n),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...Ge(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...Ge(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ge(n),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ge(n),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:ir(e)}return Tt?[...Ge(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...Ge(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},bn=({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"],a=[...i,...r],s=[...r,...i],o;if(ln)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:ir(n)}else Tt?o=s:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},da=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as tl,map as gn,Subscription as il,Subject as rl}from"@vkontakte/videoplayer-shared";var Sn=n=>new tl(e=>{let t=new il,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(gn(({from:d,to:l})=>`${d}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(gn(({type:d})=>d!==void 0)),s=new rl,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var ul={chunkDuration:5e3,maxParallelRequests:5},yi=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Se;this.noAvailableProvidersError$=new Se;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),currentVideoTrack$:new M(void 0),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),availableVideoTracks$:new M([]),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Se,warning$:new Se,willSeekEvent$:new Se,seekedEvent$:new Se,loopedEvent$:new Se,endedEvent$:new Se,firstBytesEvent$:new Se,firstFrameEvent$:new Se,canplay$:new Se,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1)};this.subscription=new yn;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=mn([...bn(this.params.tuning),...fn(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>vn(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new gi(a);let s=[...da(!0),...da(!1)];this.chromecastFormatsIterator=new gi(s.filter(o=>vn(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(sl(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:rr.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.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,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 s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return vi(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return We(o),new ui({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return We(o),new li({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return We(o),Tt||!this.params.tuning.useHlsJs?new mi({...s,source:o}):new pi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return We(o),new hi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return We(o),new fi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return We(o),new ss({...s,source:o,config:{...ul,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return We(o),new bi({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return vi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return We(o),new kt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,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 vi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return vi(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 vi(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 a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new yn,t=!1,i=0;return e.add(ol(this.providerOutput.error$,Sn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(nl(r=>({id:`ProviderHangup:${r}`,category:rr.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(al(({to:a})=>a==="playing"),dl()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===rr.NETWORK,o=r.category===rr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}})),e}};import{fromEvent as ar,once as ll,combine as cl,Subscription as Tn,ValueSubject as ua,map as pl,filter as hl,isNonNullable as sr,now as se,safeStorage as la}from"@vkontakte/videoplayer-shared";var ml=5e3,In="one_video_throughput",En="one_video_rtt",Ti=window.navigator.connection,xn=()=>{let n=Ti?.downlink;if(sr(n)&&n!==10)return n*1e3},kn=()=>{let n=Ti?.rtt;if(sr(n)&&n!==3e3)return n},Pn=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},ca=class n{constructor(e){this.subscription=new Tn;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(In)||(e.useBrowserEstimation?xn():void 0)||ml,i=n.load(En)??(e.useBrowserEstimation?kn():void 0)??0;if(this.throughput$=new ua(t),this.rtt$=new ua(i),this.rttAdjustedThroughput$=new ua(Pn(t,i,e.rttPenaltyRequestSize)),this.throughput=rt.getSmoothedValue(t,-1,e),this.rtt=rt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=xn();s&&this.throughput.next(s);let o=kn();sr(o)&&this.rtt.next(o)};Ti&&"onchange"in Ti&&this.subscription.add(ar(Ti,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{la.set(In,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{la.set(En,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(cl({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pl(({throughput:r,rtt:a})=>Pn(r,a,e.rttPenaltyRequestSize)),hl(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=se(),r=new Tn;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(ar(e,"progress").pipe(ll()).subscribe(a=>{t=a.loaded,i=se()}));break;case 1:case 0:r.add(ar(e,"loadstart").subscribe(()=>{t=0,i=se()}));break}r.add(ar(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=se(),u=s-t,d=o-i;this.addRawSpeed(u,d,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,a=se(),s=0,o=se(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,se()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(se()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)s+=c.byteLength;else{let p=o-a;p&&this.addRawSpeed(s,p,1,t),s=c.byteLength,a=se()}o=se()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&se()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,se()-o,this.concurrentDownloads.size),s=0,o=se());await i?.read().then(d,u)}};this.concurrentDownloads.add(e),i?.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*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=la.get(e);if(sr(t))return parseInt(t,10)??void 0}},An=ca;import{fillWithDefault as fl,VideoQuality as wn}from"@vkontakte/videoplayer-shared";var $n={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:wn.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:wn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Ln=n=>({...fl(n,$n),configName:[...n.configName??[],...$n.configName]});import{assertNonNullable as nr,combine as or,ErrorCategory as dr,filter as Ii,filterChanged as ce,fromEvent as ha,isNonNullable as Il,isNullable as El,Logger as xl,map as R,mapTo as Cn,merge as Ye,now as ur,once as Re,Subject as _,Subscription as Bn,tap as Vn,ValueSubject as x,isHigher as kl,isInvariantQuality as On}from"@vkontakte/videoplayer-shared";import{merge as bl,map as gl,filter as Rn,isNonNullable as Sl}from"@vkontakte/videoplayer-shared";var pa=({seekState:n,position$:e})=>bl(n.stateChangeEnded$.pipe(gl(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Rn(Sl)),e.pipe(Rn(()=>n.getState().state==="none")));import{assertNonNullable as vl}from"@vkontakte/videoplayer-shared";var Dn=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return vl(e,`Wrong container or containerId {${n.container}}`),e};import{filter as yl,once as Tl}from"@vkontakte/videoplayer-shared";var Mn=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(yl(r=>r.length>0),Tl()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var lr=class{constructor(e={configName:[]}){this.subscription=new Bn;this.logger=new xl;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped: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 x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableQualities$:new x([]),availableQualitiesFps$:new x({}),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new _,ready$:new _,started$:new _,playing$:new _,paused$:new _,stopped$:new _,willStart$:new _,willResume$:new _,willPause$:new _,willStop$:new _,willDestruct$:new _,watchCoverageRecord$:new _,watchCoverageLive$:new _,managedError$:new _,fatalError$:new _,ended$:new _,looped$:new _,seeked$:new _,willSeek$:new _,firstBytes$:new _,firstFrame$:new _,canplay$:new _,log$:new _};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Ya};if(this.initLogs(),this.tuning=Ln(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Li({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new An(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(o){let u=s.map(c=>JSON.stringify(c,(h,p)=>{let m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:dr.WTF,message:l,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Dn(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new yi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ct()?ha(document,"visibilitychange").pipe(Re()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){nr(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Ii(i=>i.length>0),Re()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){nr(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Mn(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(El(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Il(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(Ye(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(R(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Ii(({from:e})=>e==="stopped"),Re()).subscribe(()=>{this.initedAt=ur(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:dr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(R(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(R(s=>s.destination),ce()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(R(s=>s.map(({quality:o})=>o).sort((o,u)=>On(o)?1:On(u)?-1:kl(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ce()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ce()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ce()).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(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(R(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(or({hasLiveOffsetByPaused:Ye(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(R(s=>s.to),ce(),R(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(or({atLiveEdge:or({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:pa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(R(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),ce(),Vn(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(R(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(or({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(R(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ce(),Vn(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(R(s=>s.muted),ce()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(R(s=>s.volume),ce()).subscribe(this.info.volume$)).add(pa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ye(e.providerOutput.endedEvent$.pipe(Cn(!0)),e.providerOutput.seekedEvent$.pipe(Cn(!1))).pipe(ce()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(R(s=>({id:s?`No${s}`:"NoProviders",category:dr.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Re(),R(s=>s??ur()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Re(),R(()=>ur()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Re(),R(()=>ur()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new x(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Ii(({to:s})=>s==="playing"),Re()).subscribe(()=>i.next(!1)));let r=0,a=Ye(e.providerOutput.isBuffering$,t,i).pipe(R(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),ce());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ye(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ye(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?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(R(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Bn;this.subscription.add(t),this.subscription.add(e.current$.pipe(ce((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Ii(i=>i.length>0),Re()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Fe(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ye(this.desiredState.videoTrack.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(R(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;nr(this.providerContainer),nr(e),Wa(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ga(t)),this.providerContainer.current$.subscribe(({type:t})=>$t("provider",t)),e.duration$.subscribe(t=>$t("duration",t)),e.availableVideoTracks$.pipe(Ii(t=>!!t.length),Re()).subscribe(t=>$t("tracks",t)),this.events.fatalError$.subscribe(new j("fatalError")),this.events.managedError$.subscribe(new j("managedError")),e.position$.subscribe(new j("position")),e.currentVideoTrack$.pipe(R(t=>t?.quality)).subscribe(new j("quality")),this.info.currentBuffer$.subscribe(new j("buffer")),e.isBuffering$.subscribe(new j("isBuffering"))].forEach(t=>this.subscription.add(t)),$t("codecs",hn())}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:dr.DOM,message:String(r)})})};this.subscription.add(Ye(ha(document,"visibilitychange"),ha(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as aE,Observable as sE,Subject as nE,ValueSubject as oE,VideoQuality as dE}from"@vkontakte/videoplayer-shared";var uE=`@vkontakte/videoplayer-core@${fa}`;export{wi as ChromecastState,gr as HttpConnectionType,sE as Observable,re as PlaybackState,lr as Player,uE as SDK_VERSION,nE as Subject,aE as Subscription,Sr as Surface,fa as VERSION,oE as ValueSubject,qe as VideoFormat,dE as VideoQuality};
|