@vkontakte/videoplayer-core 2.0.77 → 2.0.78
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 +6 -4
- package/es2015.esm.js +6 -4
- package/es2018.cjs.js +6 -4
- package/es2018.esm.js +6 -4
- package/esnext.cjs.js +6 -4
- package/esnext.esm.js +6 -4
- package/index.d.ts +606 -8
- package/package.json +4 -4
- package/build/polyfills/runtime/abortableFetch.d.ts +0 -4
- package/build/polyfills/runtime/idleCallback.d.ts +0 -2
- package/env.d.ts +0 -2
- package/es2015.cjs.d.ts +0 -11
- package/es2015.esm.d.ts +0 -11
- package/es2018.cjs.d.ts +0 -11
- package/es2018.esm.d.ts +0 -11
- package/esnext.esm.d.ts +0 -11
- package/packages/core/src/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +0 -23
- package/packages/core/src/providers/DashIFProvider/dashjsTypes.d.ts +0 -37
- package/packages/core/src/providers/DashLiveProvider/types.d.ts +0 -14
- package/packages/core/src/providers/DashLiveProvider/utils/FilesFetcher.d.ts +0 -25
- package/packages/core/src/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -135
- package/packages/core/src/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -33
- package/packages/core/src/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +0 -42
- package/packages/core/src/providers/DashProvider/types.d.ts +0 -33
- package/packages/core/src/providers/DashProvider/utils/DashLite.d.ts +0 -60
- package/packages/core/src/providers/DashProvider/utils/stream.d.ts +0 -39
- package/packages/core/src/providers/DashProvider/utils/xhr2.d.ts +0 -15
- package/packages/core/src/providers/DashVKProvider/lib/buffer.d.ts +0 -72
- package/packages/core/src/providers/DashVKProvider/lib/ebml.d.ts +0 -71
- package/packages/core/src/providers/DashVKProvider/lib/fetcher.d.ts +0 -43
- package/packages/core/src/providers/DashVKProvider/lib/isobmff.d.ts +0 -13
- package/packages/core/src/providers/DashVKProvider/lib/mpd.d.ts +0 -2
- package/packages/core/src/providers/DashVKProvider/lib/player.d.ts +0 -47
- package/packages/core/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +0 -18
- package/packages/core/src/providers/DashVKProvider/lib/types.d.ts +0 -92
- package/packages/core/src/providers/DashVKProvider/lib/webm.d.ts +0 -3
- package/packages/core/src/providers/ProviderContainer/types.d.ts +0 -20
- package/packages/core/src/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +0 -9
- package/packages/core/src/providers/types.d.ts +0 -64
- package/packages/core/src/providers/utils/LiveOffset/index.d.ts +0 -14
- package/packages/core/src/providers/utils/LiveOffset/types.d.ts +0 -10
- package/packages/core/src/providers/utils/extractConnectionHeaders.d.ts +0 -6
- package/packages/core/src/utils/StateMachine/types.d.ts +0 -56
- package/packages/core/src/utils/StatefulIterator/StatefulIterator.spec.d.ts +0 -1
- package/packages/core/src/utils/buffer/HttpVideoBuffer.d.ts +0 -14
- package/packages/core/src/utils/buffer/getTotalBufferDuration.d.ts +0 -3
- package/packages/core/src/utils/buffer/isPositionBuffered.d.ts +0 -3
- package/packages/core/src/utils/buffer/types.d.ts +0 -4
- package/packages/core/src/utils/link.d.ts +0 -2
- package/packages/core/src/utils/quality/quality.spec.d.ts +0 -1
- package/player/Player.d.ts +0 -111
- package/player/types.d.ts +0 -430
- package/player/utils/optimisticPosition.d.ts +0 -12
- package/player/utils/selectContainer.d.ts +0 -3
- package/player/utils/watchCoverage.d.ts +0 -12
- package/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +0 -31
- package/providers/ChromecastProvider/index.d.ts +0 -33
- package/providers/DashIFProvider/BigRequestLoader.d.ts +0 -41
- package/providers/DashIFProvider/endOfStreamHack.d.ts +0 -3
- package/providers/DashIFProvider/index.d.ts +0 -37
- package/providers/DashIFProvider/observableManifestLoader.d.ts +0 -11
- package/providers/DashIFProvider/requestQuic.d.ts +0 -3
- package/providers/DashIFProvider/stripRangeHeader.d.ts +0 -3
- package/providers/DashLiveProvider/DashLiveProvider.d.ts +0 -36
- package/providers/DashLiveProvider/index.d.ts +0 -2
- package/providers/DashProvider/DashProvider.d.ts +0 -32
- package/providers/DashProvider/index.d.ts +0 -2
- package/providers/DashVKProvider/index.d.ts +0 -23
- package/providers/DashVKProvider/lib/player.d.ts +0 -47
- package/providers/DashVKProvider/lib/types.d.ts +0 -92
- package/providers/HlsJsProvider/index.d.ts +0 -24
- package/providers/HlsLiveProvider/index.d.ts +0 -28
- package/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +0 -3
- package/providers/HlsProvider/index.d.ts +0 -20
- package/providers/HlsProvider/qualityExtractor.d.ts +0 -12
- package/providers/MpegProvider/index.d.ts +0 -19
- package/providers/ProviderContainer/index.d.ts +0 -69
- package/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -4
- package/providers/ProviderContainer/utils/playbackHangup.d.ts +0 -11
- package/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +0 -188
- package/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +0 -60
- package/providers/utils/HtmlVideoTextTrackManager.d.ts +0 -23
- package/providers/utils/addQuicParam.d.ts +0 -2
- package/providers/utils/forcePlay.d.ts +0 -7
- package/providers/utils/generateLiveUrl.d.ts +0 -7
- package/providers/utils/initVideoInContainer.d.ts +0 -2
- package/providers/utils/observableVideo.d.ts +0 -24
- package/providers/utils/okQualityStringToVideoQuality.d.ts +0 -3
- package/providers/utils/parseFps.d.ts +0 -1
- package/providers/utils/syncDesiredState.d.ts +0 -12
- package/providers/utils/syncPlaybackState.d.ts +0 -4
- package/utils/StateMachine/StateMachine.d.ts +0 -17
- package/utils/StatefulIterator/index.d.ts +0 -13
- package/utils/ThroughputEstimator.d.ts +0 -25
- package/utils/addScript.d.ts +0 -2
- package/utils/autoSelectVideoTrack.d.ts +0 -24
- package/utils/buffer/getBufferedRangeForPosition.d.ts +0 -3
- package/utils/buffer/getForwardBufferDuration.d.ts +0 -3
- package/utils/hostnameFromUrl.d.ts +0 -2
- package/utils/iframeSafeStorage.d.ts +0 -5
- package/utils/isSafari.d.ts +0 -2
- package/utils/observeElementSize.d.ts +0 -3
- package/utils/playbackTelemetry.d.ts +0 -12
- package/utils/quality/types.d.ts +0 -21
- package/utils/quality/utils.d.ts +0 -20
- package/utils/smoothedValue.d.ts +0 -28
- package/utils/tuningConfig.d.ts +0 -75
- package/utils/videoFormat.d.ts +0 -2
package/esnext.esm.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Thu,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.78
|
|
3
|
+
* Thu, 02 Feb 2023 10:14:35 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-78/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,ErrorCategory as a,isNullable as r,fromEvent as n,assertNever as o,merge as d,tap as h,map as u,observableFrom as c,filterChanged as l,assertNonNullable as p,debounce as m,timeout as f,combine as g,once as S,mapTo as b,filter as v,now as y,Observable as T,abortable as E,getExponentialDelay as w,interval as $,Logger as k}from'@vkontakte/videoplayer-shared/esnext.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/esnext.esm.js';import A from'lodash/debounce.js';var P,R,D,_,I,C;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS',t.HLS_LIVE='HLS_LIVE',t.WEB_RTC_LIVE='WEB_RTC_LIVE'}(R||(R={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(D||(D={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(I||(I={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(C||(C={}));class L{connection$=new t(void 0);castState$=new t(_.NOT_AVAILABLE);errorEvent$=new e;contentId;realCastState$=new t(_.NOT_AVAILABLE);subscription=new i;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const e='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${e}`}),t.isDisabled||!e)return;const i=s(window.chrome?.cast),r=Boolean(window.__onGCastApiAvailable);var n;i?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{delete window.__onGCastApiAvailable,t&&this.initializeCastApi()},r||(n='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',n),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',category:a.NETWORK,message:'Script loading failed!'}))))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();r(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();r(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(n(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{switch(t.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 o(t.sessionState)}}))).add(d(n(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(h((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),c([i.getCastState()])).pipe(l(),u(x),h((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{const n=a===_.CONNECTED,o=s(this.connection$.getValue());if(n&&!o){const s=i.getCurrentSession();p(s);const a=s.getCastDevice(),n=s.getMediaSession()?.media.contentId;(r(n)||n===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===_.CONNECTED?s(this.connection$.getValue())?_.CONNECTED:_.AVAILABLE:a)})))}initializeCastApi(){let t,e,i;try{t=cast.framework.CastContext.getInstance(),e=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{t.setOptions({receiverApplicationId:this.params.receiverApplicationId??e,autoJoinPolicy:i}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',category:a.EXTERNAL_API,message:'[initializeCastApi] failed',thrown:t})}}}const x=t=>{switch(t){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 o(t)}};var N;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(N||(N={}));var B,O=(t,e=0,i=N.OFFSET_P)=>{switch(i){case N.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case N.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:o(i)}return t},M=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(B||(B={}));const U={[B.Q_144P]:{width:256,height:144},[B.Q_240P]:{width:428,height:240},[B.Q_360P]:{width:640,height:360},[B.Q_480P]:{width:856,height:480},[B.Q_720P]:{width:1280,height:720},[B.Q_1080P]:{width:1920,height:1080},[B.Q_1440P]:{width:2560,height:1440},[B.Q_2160P]:{width:3840,height:2160},[B.Q_4320P]:{width:7680,height:4320}},V=(t,e)=>U[t].height>U[e].height,F=(t,e)=>U[t].height<U[e].height,q=Object.keys(U).sort(((t,e)=>F(t,e)?-1:1)),H=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return q.find((t=>{const e=U[t];return e.width>=s&&e.height>=i}))},G=t=>t===B.INVARIANT;class Y{state;transition;transitionStarted$=new e;transitionEnded$=new e;transitionUpdated$=new e;forceChanged$=new e;stateChangeStarted$=d(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=d(this.transitionEnded$,this.forceChanged$);constructor(t){this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var z;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(z||(z={}));class Q{subscription=new i;loadMediaTimeoutSubscription=new i;videoState=new Y(z.STOPPED);params;log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case R.MPEG:case R.DASH:case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:case R.HLS:case R.HLS_ONDEMAND:return!1;case R.HLS_LIVE:case R.DASH_LIVE:case R.DASH_LIVE_WEBM:case R.WEB_RTC_LIVE:return!0;default:return o(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(d(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const s=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(m(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),t.add(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),a=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==a&&this.params.output.isBuffering$.next(a),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),M(this.params.desiredState.playbackState,P.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:o(i)}})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(n(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(d(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(z.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(z.PLAYING),M(this.params.desiredState.playbackState,P.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==z.PAUSED&&t!==z.PLAYING||(this.videoState.setState(z.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState();this.videoState.getTransition()?.to!==z.PLAYING&&t!==z.PAUSED||(this.videoState.setState(z.PLAYING),M(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY)}handleRemoteStop(){this.videoState.getState()!==z.STOPPED&&this.videoState.setState(z.STOPPED)}handleRemoteVolumeChange(t){const e=this.params.output.volume$.getValue(),i={volume:t.volume??e.volume,muted:t.muted??e.muted};i.volume===e.volume&&i.muted==i.muted||this.params.output.volume$.next(i)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){const e=this.params.source;let i,r,n;switch(t){case R.MPEG:{const s=e[t];p(s);const a=Object.keys(s).sort(((t,e)=>t===e?0:t===B.INVARIANT?1:e===B.INVARIANT?-1:F(t,e)?1:-1))[0];p(a);const o=s[a];p(o),i=o,r='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS:case R.HLS_ONDEMAND:{const s=e[t];p(s),i=s.url,r='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case R.DASH_SEP:case R.DASH_ONDEMAND:case R.DASH_WEBM:{const s=e[t];p(s),i=s.url,r='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case R.HLS_LIVE:{const s=e[t];p(s),i=O(s.url),r='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case R.DASH:case R.DASH_LIVE:case R.WEB_RTC_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',category:a.VIDEO_PIPELINE,message:t,thrown:e}),e}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return o(t)}const d=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);d.contentUrl=i,d.streamType=n,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:h,subtitle:u}=this.params.meta;return s(h)&&(d.metadata.title=h),s(u)&&(d.metadata.subtitle=u),d}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===C.Applying||i.state===C.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(f(7e3).subscribe((()=>e('timeout(7000)'))))}));Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',category:a.VIDEO_PIPELINE,message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)if(s?.to===P.PAUSED||a.state!==C.Requested||t===z.STOPPED)switch(i){case P.PLAYING:switch(t){case z.PLAYING:break;case z.PAUSED:case z.READY:this.videoState.startTransitionTo(z.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();break;default:o(t)}break;case P.PAUSED:switch(t){case z.PLAYING:this.videoState.startTransitionTo(z.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case z.PAUSED:break;case z.READY:this.videoState.startTransitionTo(z.PAUSED),this.videoState.setState(z.PAUSED);break;case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();break;default:o(t)}break;default:o(i)}else this.seek(a.position)}else t!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.stop())}}class W{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class j extends W{constructor(){super(),this.listeners||W.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class J{constructor(){Object.defineProperty(this,'signal',{value:new j,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function X(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(J.prototype[Symbol.toStringTag]='AbortController',j.prototype[Symbol.toStringTag]='AbortSignal');const K=X({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Z=K?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=t;if(!X({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:r};let r=i;(r&&!r.prototype.hasOwnProperty('signal')||a)&&(r=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const a=new i(t,e);return s&&Object.defineProperty(a,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),a},r.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=r&&r.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const a=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([a,n(t,e)])}return n(t,e)},Request:r}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,tt=K?Z.fetch:window.fetch;K?Z.Request:window.Request;const et=K?J:window.AbortController,it=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class st{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){const{url:e}=t.request,i=this.dashJsRequestQueue.get(e)??[];i.push(t),this.dashJsRequestQueue.set(e,i)}async executeNextRequests(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[a,r]=it(s.request);if(a>=i.from&&r<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}abort(t){if(t){const{request:e}=t,i=(this.dashJsRequestQueue.get(e.url)??[]).includes(t),s=this.activeRequests.get(e.url);i&&s&&s.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(it),s=i[0][0];let r=i[0][1];for(let t=1;t<i.length&&r<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===s?Math.max(r,s+this.params.minInitSize):Math.max(r,s+this.params.minDataSize);const n=new URL(t,location.href);n.searchParams.append('bytes',`${s}-${r}`);const o=n.toString(),d=new et,h=d.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:d};h.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const c=t=>{throw this.params.onError?.({id:'BigRequestParsing',category:a.PARSER,message:'Error parsing response data',thrown:t}),t};return tt(o,{signal:h}).then((t=>{if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[e,i]=t.body.tee();this.params.onDownloadStream?.(i);const a=e.getReader(),n=parseInt(t.headers.get('Content-Length')??'',10)||r-s+1;u.data=new ArrayBuffer(n);const o=new Uint8Array(u.data),d=async({done:t,value:e})=>{t?this.onBigRequestProgress(u):e&&(o.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),await(a?.read().then(d,st.suppressStreamErrors).catch(c)))};a?.read().then(d,st.suppressStreamErrors).catch(c)}),st.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:a,response:r}){if(!this.activeRequests.has(t)||!a)return;const n=this.dashJsRequestQueue.get(t)??[];for(const o of n){const{request:n}=o,[d,h]=it(n),u=d>=e&&h<=e+s,c=e>=d&&e+s<h,l=a.slice(d-e,Math.min(h-e+1,s));if((u||c)&&(n.requestStartDate=n.requestStartDate??new Date,n.firstByteDate=n.firstByteDate??new Date,n.bytesLoaded=l.byteLength,n.bytesTotal=i-e),u){n.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(this.dashJsRequestQueue.get(t)??[]).filter((t=>t!==o))),o.success?.(l,'',t);const e=r?Array.from(r.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';this.dashMetrics?.addHttpRequest(n,t,r?.status??200,e,[])}else c&&o.progress?.({loaded:s,total:i-e,lengthComputable:!0,stream:!0})}}onBigRequestError({url:t,from:e,to:i},s){if(this.params.onError?.({id:'BigRequest',category:a.NETWORK,message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const r=this.dashJsRequestQueue.get(t)??[];for(const t of r){const[a,r]=it(t.request);(a>=e&&a<i||r>e&&r<=i)&&t?.error?.(t.request,String(s))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){if(!this.activeRequests.has(t))return;const s=this.dashJsRequestQueue.get(t)??[];for(const t of s){const[s,a]=it(t.request);(s>=e&&s<i||a>e&&a<=i)&&t?.abort?.(t.request)}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class at{baseLoader;config;bigRequest;constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(at.shouldDelegateToBase(e))return this.baseLoader.load(t);this.bigRequest.queueDashJSRequest(t),this.bigRequest.executeNextRequests()}abort(t){if(!t)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:e}=t;at.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const rt=(t,e)=>{const i=new st(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const a=t(i).create(s);return new at(a,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var nt=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&e?.()})),t.extend('MediaSourceController',(function(){const{parent:t}=this,a=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>a(t),i&&s&&e?.()}}}),!0)},ot=i=>{const a=new t(1/0),r=new e,n=new t(void 0),o=new t(void 0);let d=NaN,h=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{const e=Object.fromEntries(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in e||'x-playback-duration-millis'in e){const e=parseInt(t.getResponseHeader('X-Playback-Duration')??'',10),i=parseInt(t.getResponseHeader('X-Playback-Duration-Millis')??'',10)??1e3*e??NaN;s(i)&&!isNaN(i)&&a.next(i)}const i=e['x-delivery-type']??I.HTTP1,r={1:!0,0:!1}[e['x-reused']]??void 0;n.next(i),o.next(r)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!h&&(h=!0,r.next(Date.now()-d)),i(...t)},d=Date.now(),h=!1}return e(t)}}}),!0),{playbackDuration$:a,ping$:r,connectionReused$:o,connectionType$:n}},dt=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},ht=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,i]=t.request.range.split('-').map((t=>parseInt(t,10))),s=new URL(t.request.url,location.href);s.searchParams.append('bytes',`${e}-${i}`),t.request.url=s.toString(),t.request.range=void 0}e(t)}}}),!0)};const ut=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),h=e(),u=r(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(h,d)||(s(d),u&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),u&&t.setState(e.to)}),o)),c},ct=(t,e,i)=>ut(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),lt=(t,e,i,a)=>ut(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||t?.muted===e?.muted&&t?.volume===e?.volume,changed$:i,onError:a}),pt=(t,e,i,a)=>ut(e,(()=>t.playbackRate),(e=>{s(e)&&(t.playbackRate=e)}),{changed$:i,onError:a}),mt=(t,e)=>{if(t.id===e)return!0;const[i,s,a]=e.split('|');return t.language===s&&t.label===a};class ft{available$=new e;current$=new t(void 0);error$=new e;video;cueSettings;subscription=new i;externalTracks=new Map;connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',category:a.WTF,message:'Generic HtmlVideoTextTrackManager error',thrown:t})};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(ut(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(ut(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add(ut(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){p(this.video);const{textTracks:t}=this.video;this.subscription.add(n(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(d(n(t,'addtrack'),n(t,'removetrack'),c(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),l(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(d(n(t,'change'),c(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),l()).subscribe(this.current$));const e=t=>this.applyCueSettings(t.target?.activeCues??null);this.subscription.add(n(t,'addtrack').subscribe((t=>{t.track?.addEventListener('cuechange',e);const i=t=>{const e=t.target?.cues??null;e&&e.length&&(this.applyCueSettings(t.target?.cues??null),t.target?.removeEventListener('cuechange',i))};t.track?.addEventListener('cuechange',i)}))),this.subscription.add(n(t,'removetrack').subscribe((t=>{t.track?.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){p(this.video);const e=[...this.video.textTracks];return t?e:e.filter(ft.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){p(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&mt(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){p(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){p(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var gt=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),e.setAttribute('poster','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='),t.appendChild(e),e};class St{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(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}var bt=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};class vt{_buffer=[];_source;constructor(t){this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:a})=>{const r=s>=t&&s<e,n=a>=t&&a<e;r&&n||(r?i(e,a):n?i(s,t):s<t&&a>e?(i(e,a),i(s,t)):i(s,a))}))}destroy(){this._buffer=[]}}var yt=(t,e,i=3)=>{let s=0,a=0;for(let r=0;r<t.length;r++){const n=t.start(r),o=t.end(r);if(n<=e&&e<=o){if(s=n,a=o,!i)return{from:s,to:a};for(let e=r-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=r+1;e<t.length;e++)t.start(e)-i<=a&&(a=t.end(e))}}return{from:s,to:a}};const Tt=t=>{const i=e=>n(t,e).pipe(b(void 0)),r=d(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>n(t,e)))).pipe(u((e=>'ended'===e.type?t.readyState<2:t.readyState<3)),l()),o=d(n(t,'progress'),n(t,'timeupdate')).pipe(u((()=>yt(t.buffered,t.currentTime)))),h=bt()?g({play:i('play').pipe(S()),playing:i('playing')}).pipe(b(void 0)):i('playing'),c=n(t,'volumechange').pipe(u((()=>({muted:t.muted,volume:t.volume})))),p=n(t,'ratechange').pipe(u((()=>t.playbackRate))),m=n(t,'error').pipe(v((()=>Boolean(t.error||t.played.length))),u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',category:a.VIDEO_PIPELINE,message:e?e.message:'Error event from HTML video element',thrown:t.error??void 0}}))),f=n(t,'timeupdate').pipe(u((()=>t.currentTime))),y=new e;let T;return f.subscribe((e=>{t.loop&&s(T)&&s(e)&&T>=t.duration-.3&&e<=.3&&y.next(T),T=e})),{playing$:h,pause$:i('pause').pipe(v((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:y,error$:m,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:f,durationChange$:n(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:r,currentBuffer$:o,volumeState$:c,playbackRateState$:p}},Et=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};let wt=!1,$t={};const kt=t=>{t($t)},At=(t,e)=>{wt&&($t.meta=$t.meta??{},$t.meta[t]=e)};class Pt{name;constructor(t){this.name=t}next(t){if(!wt)return;$t.series=$t.series??{};const e=$t.series[this.name]??[];e.push([Date.now(),t]),$t.series[this.name]=e}}const Rt=new Pt('best_bitrate');class Dt{last;history={};recordSelection(t){this.history[t.id]=y()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const _t=(t,{container:e,throughput:i,tuning:a,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:h,current:u,history:c})=>{const l=a.usePixelRatio?window.devicePixelRatio??1:1,p=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*l*a.containerSizeFactor,height:e.height*l*a.containerSizeFactor},m=p&&H(p),f=a.considerPlaybackRate&&s(h)?h:1,g=t.filter((t=>!G(t.quality))).sort(((t,e)=>V(t.quality,e.quality)?-1:1)),S=g.at(-1)?.quality,b=g.at(0)?.quality,v=r(n)||s(n.min)&&s(n.max)&&F(n.max,n.min)||s(n.min)&&b&&V(n.min,b)||s(n.max)&&S&&F(n.max,S),T=f*(E=d??.5,w=a.bitrateFactorAtEmptyBuffer,$=a.bitrateFactorAtFullBuffer,(w-$)*Math.pow(2,-10*E)+$);var E,w,$;const k=g.filter((t=>{const e=!m||F(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*T,c=a.lazyQualitySwitch&&s(a.minBufferToSwitchUp)&&u&&!G(u.quality)&&(d??0)<a.minBufferToSwitchUp&&V(t.quality,u.quality),l=v||(r(n.max)||(p=t.quality,f=n.max,U[p].height<=U[f].height))&&(r(n.min)||((t,e)=>U[t].height>=U[e].height)(t.quality,n.min));var p,f;return e&&h&&!c&&l}))[0];k&&k.bitrate&&Rt.next(k.bitrate);const A=k??g[Math.ceil((g.length-1)/2)]??t[0],P=A&&c&&c.history[A.id]&&y()-c.history[A.id]<=a.trackCooldown&&(!c.last||A.id!==c.last.id);if(A?.id&&c&&!P&&c.recordSelection(A),P&&c?.last){const t=c.last;return c?.recordSwitch(t),t}return c?.recordSwitch(A),A};var It=t=>new URL(t).hostname;const Ct=(t,e=300)=>new T((i=>{const{width:a,height:r}=t.getBoundingClientRect();if(i.next({width:a,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let a,r;e.contentBoxSize&&e.contentBoxSize[0]?(r=e.contentBoxSize[0].blockSize,a=e.contentBoxSize[0].inlineSize):e.contentRect&&(a=e.contentRect.width,r=e.contentRect.height),s(a)&&s(r)&&i.next({width:a,height:r})}),e));return n.observe(t),()=>n.disconnect()})),Lt={};var xt;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xt||(xt={}));const Nt=(t,e)=>new T((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Bt{subscription=new i;videoState=new Y(xt.DOWNLOADING_LIB);video;player;params;textTracksManager=new ft;videoTracks=[];frameRatesByFrameHeight={};isLive$=new t(void 0);maxSeekBackTime$=new t(1/0);availableFrom$=new t(void 0);elementSize$=new t(void 0);liveOffset=new St;destroyBigRequest;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',category:a.NETWORK,message:`Dash.js failed to load: ${e?.toString?.()}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Lt.MediaPlayer=e.MediaPlayer,Lt.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){p(Lt.MediaPlayer,'dashjs not loaded'),p(Lt.Debug,'dashjs not loaded'),this.player=Lt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter((t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Et(t.frameRate+''):void 0),!0)));(this.params.format===R.DASH_WEBM||this.params.format===R.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=rt(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&ht(this.player),nt(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:dt})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(xt.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',category:a.WTF,message:'DashIFProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(Ct(this.video),this.elementSize$),n(Nt(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),n(Nt(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const o=Nt(this.player,'qualityChangeRendered').pipe(v((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track)));o.pipe(v(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(v((({to:t})=>t===xt.STREAM_INITIALIZED)),S()).subscribe((()=>{this.subscription.add(ut(e.videoTrack,(()=>{const t=this.player.getQualityFor('video');return this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t))?.track?.id}),(t=>{if(r(t))return;const e=this.videoTracks.find((({track:e})=>e.id===t))?.bitrateInfo;e&&this.player.setQualityFor('video',e.qualityIndex)}),{changed$:o.pipe(u((t=>t?.id))),onError:i}))}),i)),this.subscription.add(ut(e.autoVideoTrackSwitching,(()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),n(Nt(this.player,'bufferStateChanged').pipe(v((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),n(Nt(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{const s=this.player.getDashMetrics(),a=s.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),r=s.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type')??I.HTTP1,n={1:!0,0:!1}[a]??void 0;this.params.output.httpConnectionType$.next(r),this.params.output.httpConnectionReused$.next(n),t.hostname$.next(It(i))})),n(Nt(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const a=this.player.getQualityFor('video');let r;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=H(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===a&&(r=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),r&&t.currentVideoTrack$.next(r),this.videoState.setState(xt.STREAM_INITIALIZED),this.videoState.startTransitionTo(xt.READY)})),n(Nt(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),n(d(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=_t(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));s?.bitrateInfo&&this.player.setQualityFor('video',s?.bitrateInfo.qualityIndex,!1)})),n(g({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(v(s))}).pipe(v((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const h=Nt(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>t??0)));n(g({availableFrom:this.availableFrom$.pipe(v(s)),currentTime:h}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),n(h.pipe(v((()=>!1===this.isLive$.getValue()))),t.position$),n(Nt(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),n(Nt(this.player,'playbackEnded'),t.endedEvent$),n(Nt(this.player,'playbackProgress').pipe(u((()=>yt(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),n(Nt(this.player,'playbackPlaying'),(()=>{this.videoState.setState(xt.PLAYING),M(e.playbackState,P.PLAYING)})),n(Nt(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(xt.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),n(Nt(this.player,'playbackPaused'),(()=>{this.videoState.setState(xt.PAUSED),M(e.playbackState,P.PAUSED)})),n(Nt(this.player,'canPlay'),(()=>{this.videoState.getTransition()?.to===xt.READY&&this.videoState.setState(xt.READY)})),n(this.isLive$,t.isLive$),n(Ct(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));n(d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)),this.syncPlayback);const{playbackDuration$:l,ping$:p,connectionType$:f,connectionReused$:y}=ot(this.player);n(f,this.params.output.httpConnectionType$),n(y,this.params.output.httpConnectionReused$),n(l,this.maxSeekBackTime$),n(p.pipe(S()),t.firstBytesEvent$),n(Nt(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&n(g({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),n(h.pipe(v((t=>t>this.params.tuning.insufficientBufferRuleMargin)),S()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Nt(this.player,'manifestLoaded').pipe(S()).subscribe((()=>{this.subscription.add(Nt(this.player,'playbackPlaying').pipe(S(),b(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(ct(this.video,e.isLooped,i));const{volumeState$:T,looped$:E,playbackRateState$:w}=Tt(this.video);this.subscription.add(lt(this.video,e.volume,T,i)),this.subscription.add(T.subscribe(t.volume$,i)),this.subscription.add(E.subscribe(t.loopedEvent$)),this.subscription.add(pt(this.video,e.playbackRate,w,i))}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.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(xt.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(xt.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=O(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,N.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(xt.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(xt.PAUSED),this.video.pause()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==xt.DOWNLOADING_LIB&&t!==xt.STREAM_INITIALIZED)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&t!==xt.STOPPED&&e!==P.STOPPED&&(a?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case xt.STOPPED:break;case xt.PLAYING:case xt.PAUSED:case xt.READY:this.stop();break;default:o(t)}break;case P.PLAYING:switch(t){case xt.PLAYING:break;case xt.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case xt.READY:this.play();break;case xt.STOPPED:this.prepare();break;default:o(t)}break;case P.PAUSED:switch(t){case xt.PLAYING:this.pause(),this.liveOffset.pause();break;case xt.PAUSED:break;case xt.READY:this.videoState.setState(xt.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED);break;case xt.STOPPED:this.prepare();break;default:o(t)}break;default:o(e)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Ot=t=>{switch(t){case'mobile':return B.Q_144P;case'lowest':return B.Q_240P;case'low':return B.Q_360P;case'sd':case'medium':return B.Q_480P;case'hd':case'high':return B.Q_720P;case'fullhd':case'full':return B.Q_1080P;case'quadhd':case'quad':return B.Q_1440P;case'ultrahd':case'ultra':return B.Q_2160P}},Mt=async t=>{const e=t.muted;try{await t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{await t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0};function Ut(){return y()}function Vt(t){return Ut()-t}function Ft(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,a=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let r=t.indexOf('?')>-1?'&':'?';return a&&(t+=r+'lowLat=1',r='&'),e&&(t+=r+'_rnd='+Math.floor(999999999*Math.random())),t}}}function qt(t,e,i,a){const r=window.XMLHttpRequest;let n,o,d,h,u,c=!1,l=0,m=!1,f='arraybuffer',g=7e3,S=2e3,b=()=>{if(c)return;p(h);const t=Vt(h);let e;if(t<S)return e=S-t,void setTimeout(b,e);S*=2,S>g&&(S=g),o&&o.abort(),o=new r,y()};const v=()=>{if(!c){if(--l>=0)return b(),void(a&&a());c=!0,u&&u(),i&&i()}},y=()=>{h=Ut(),o=new r,o.open('get',t);let i,s=0,a=0;const l=()=>(p(h),Math.max(h,Math.max(i||0,a||0)));if(n&&o.addEventListener('progress',(t=>{const e=Ut();n.updateChunk&&t.loaded>s&&(n.updateChunk(l(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>v()))),o.addEventListener('load',(()=>{if(c)return;p(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(l(),t)}u&&u(),o&&e(o.response)}else v()})),o.addEventListener('error',(()=>{v()})),m){const t=()=>{p(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(a=Ut(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=f,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(m=t,T),withJSONResponse:()=>(f='json',T),withRetryCount:t=>(l=t,T),withRetryInterval:(t,e)=>(s(t)&&(S=t),s(e)&&(g=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(u=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,u&&u()}};return T}class Ht{intervals=[];currentRate=0;logger;constructor(t){this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const a=e-t.start,r=t.end-t.start;i+=a;const n=t.bytes*a/r;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const a=8*s/(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(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,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}}class Gt{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(t,e,i,s,a){this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=a}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=Ut(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=qt(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ut()-i,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(s,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>s('error')),(()=>{t._retry=1,t._retryCB&&t._retryCB()})),t._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{t._finallyCB&&t._finallyCB()})),this.activeRequests[e]=t,t._request.send(),this.lastPrefetchStart=Ut()}_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 t=this._getParallelRequestCount(),e=Ut();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const a={};return a.send=()=>{const r=this.activeRequests[t]||this.completeRequests[t];if(r)r._cb=e,r._errorCB=i,r._retryCB=s,r._finallyCB=a._finallyCB,r._error||r._complete?(this._removeFromActive(t),setTimeout((()=>{r._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(r._responseData,r._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(r._errorMsg)),a._finallyCB&&a._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(a,t)}},a._cb=e,a._errorCB=i,a._retryCB=s,a.abort=function(){a.request&&a.request.abort()},a.withFinally=t=>(a._finallyCB=t,a),a}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Yt{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(t){this.params=t,this.chunkRateEstimator=new Ht(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Ft(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}setMaxAutoQuality(t){this.maxAutoQuality=t}switchByName(t){let e;for(let i=0;i<this.manifest.length;++i)if(e=this.manifest[i],e.name===t)return void this._switchToQuality(e)}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(t){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(t):this._notifyBuffering(!0)):this.catchUp()}startPlay(t,e){this.autoQuality=e,this._initPlayerWith(t)}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(t){this.manifestUrl=t,this.urlResolver=Ft(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(()=>{Boolean(t.error)&&!this.destroyed&&(e(`Video element error: ${t.error?.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)}),1e3*(t+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,a;const r=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)a=this.manifest[e],this.maxAutoQuality&&a.video.height>this.maxAutoQuality||(a.bitrate<t&&r>Math.min(a.video.height,a.video.width)?(!s||a.bitrate>s.bitrate)&&(s=a):(!i||i.bitrate>a.bitrate)&&(i=a));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:a}=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(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const r=()=>{!function(t,e,i){const s=(...a)=>{i.apply(null,a),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),a({name:'playing'})):r()}))};r()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gt(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,d=null,h=null,u=null,c=!1;const l=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{h&&h.abort(),h=qt(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{h=null})).send()},f=(t,e,i)=>{p(this.filesFetcher),d?.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},g=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},S=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),b()},b=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void g(1);const i=Ut()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const a=this.bufferStates[e];t=Math.min(t,a.buf),a.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let a=t-1;this.sourceJitter>=0?a-=this.sourceJitter/2:this.sourceJitter-=1,g(a>3?1.15:a>1?1.1:a>.3?1.01:1)}else g(1)},v=t=>{let i;const r=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,h=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,a=e;this.sourceJitter>1&&(a+=this.sourceJitter-1);let r=i.dur.length-1;for(;r>=0&&(a-=i.dur[r],!(a<=0));--r);t=Math.min(r,i.dur.length-1-s),t=Math.max(t,0)}return h(t,!0)},m=(t,e,i)=>{u&&u.abort(),u=qt(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{u=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!l())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&S(d);let u=0;for(let t=0;t<i.dur.length;++t)u+=i.dur[t];u>0&&(p(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(u/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=r();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return h(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=r(),a=t?t.chunkIdx+1:0,n=a-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return h(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),h&&h.abort(),u&&u.abort(),p(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,h,c,g,S,T,E=v(t.jidxUrl),w=0;const $=()=>{g&&(clearTimeout(g),g=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Ut(),s=Math.min(1e4,e-i);w=i;const a=()=>{u||l()&&E.seek((()=>{l()&&(w=Ut(),k(),$())}))};s>0?g=window.setTimeout((()=>{this.paused?$():a()}),s):a()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,_(e);const i=E.nextChunk(h);if(i){if(h&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));D(i)}else $()},A=(t,e)=>{if(!l()||!this.sourceBuffer)return;let a,r,n;const o=i=>{window.setTimeout((()=>{l()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Ut(),h=i.currentTime;!this.paused&&i.buffered.length>1&&S===h&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),S!==h&&(S=h,T=d);const u=this._getBufferSizeSec();if(u>30)s(`Buffered ${u} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:u}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(a=this.sourceBuffer.buffered.start(0),r=h,r-a>4&&this.sourceBuffer.remove(a,r-3)),o(1e3)}}},P=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(h)]),A(d,(function(){d=null,k()})))},R=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{l()&&f(R(t),((e,i)=>{if(l()){if(i/=1e3,d=e,h=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},_=t=>{l()&&(p(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(R(t),!1)))},I=e=>{l()&&(t.cachedHeader=e,A(e,(()=>{a=!0,P()})))};n=!0,E.seek((t=>{l()&&(w=Ut(),t?(c=t,!r(e)||t.startTS>e?D(t):(h=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let a;t.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),s(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,p(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,a;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),a=e/this.bitrate,s>10&&a>.8||s>15&&a>.5||s>20&&a>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Ut();if(this.chunkRateEstimator.addInterval(t,s,i)){const a=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:a}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let a,r=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&a&&this.autoQuality){if(n&&t>a&&Vt(r)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Ut();t<a&&(r=e),a=t}}}_fetchManifest(t,e,i){this.manifestRequest=qt(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;Mt(e).then((e=>{e||t?.()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return t?.length?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var zt;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(zt||(zt={}));const Qt=[zt.PAUSED,zt.PLAYING,zt.READY],Wt=[zt.PAUSED,zt.PLAYING,zt.READY];class jt{subscription=new i;video;videoState=new Y(zt.STOPPED);dash;representations$=new t([]);textTracksManager=new ft;maxSeekBackTime$=new t(1/0);zeroTime$=new t(void 0);liveOffset=new St;log;params;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const e=e=>{t.output.error$.next({id:'DashLiveProvider',category:a.WTF,message:'DashLiveProvider internal logic error',thrown:e})};d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.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.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Tt(this.video);this.subscription.add(i.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===zt.READY&&this.videoState.setState(zt.READY)}),e)).add(i.pause$.subscribe((()=>{this.videoState.setState(zt.PAUSED)}),e)).add(i.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(zt.PLAYING)}),e)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(l(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(g({zeroTime:this.zeroTime$.pipe(v(s)),position:i.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),e)).add(ct(this.video,this.params.desiredState.isLooped,e)).add(lt(this.video,this.params.desiredState.volume,i.volumeState$,e)).add(i.volumeState$.subscribe(this.params.output.volume$,e)).add(pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,e)).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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&U[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case zt.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case zt.MANIFEST_READY:case zt.READY:break;case zt.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case zt.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return o(t.to)}}),e)).add(d(t.desiredState.playbackState.stateChangeStarted$,t.desiredState.seekState.stateChangeEnded$,t.desiredState.videoTrack.stateChangeStarted$,t.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)).subscribe(this.syncPlayback,e))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Yt({videoElement:this.video,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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){const t=this.representations$.getValue(),e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&s(e)?e:_t(t.map((({track:t})=>t)),{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()})?.id,r=t.find((({track:t})=>t.id===a))?.representation;p(r,'Representations missing'),this.dash.startPlay(r,i),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(i)}setVideoTrack(t){const e=this.representations$.getValue().find((({track:e})=>e.id===t))?.representation;p(e,`No such representation ${t}`),this.dash.switchByName(e.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(O(this.params.source.url,i))}_dashCb=t=>{switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,category:a.WTF,message:'LiveDashPlayer reported error'});break;case'manifest':{const e=t.manifest,i=[];for(const t of e){const e=t.name??t.index.toString(10),s=Ot(t.name)??H(t.video),a=t.bitrate/1e3,r={...t.video};if(!s)continue;const n={id:e,quality:s,bitrate:a,size:r};i.push({track:n,representation:t})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map((({track:t})=>t))),this.videoState.getTransition()?.to===zt.MANIFEST_READY&&this.videoState.setState(zt.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=this.representations$.getValue().find((({representation:t})=>t===e))?.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}};syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e){if(Wt.includes(t)){const t=this.params.desiredState.videoTrack.getTransition()?.to;s(t)&&this.setVideoTrack(t);const e=this.params.desiredState.autoVideoTrackSwitching.getTransition();e&&this.setAutoQuality(e.to)}if(a?.to!==P.PAUSED&&r.state===C.Requested&&Qt.includes(t))this.seek(r.position-this.liveOffset.getTotalPausedTime());else switch(t){case zt.STOPPED:return this.videoState.startTransitionTo(zt.MANIFEST_READY),void this.dash.attachSource(O(this.params.source.url));case zt.MANIFEST_READY:this.videoState.startTransitionTo(zt.READY),this.prepare();break;case zt.READY:return void(i===P.PAUSED?this.videoState.setState(zt.PAUSED):i===P.PLAYING&&(this.videoState.startTransitionTo(zt.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zt.PAUSED)}))));case zt.PLAYING:return void(i===P.PAUSED&&(this.videoState.startTransitionTo(zt.PAUSED),this.liveOffset.pause(),this.dash.pause()));case zt.PAUSED:return void(i===P.PLAYING&&(this.videoState.startTransitionTo(zt.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zt.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return o(t)}}}else t!==zt.STOPPED&&(this.videoState.startTransitionTo(zt.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(zt.STOPPED))}}var Jt=t=>{const e=t.get('X-Delivery-Type'),i=t.get('X-Reused');return{type:null===e?I.HTTP1:e??void 0,reused:null===i?void 0:{1:!0,0:!1}[i]??void 0}},Xt=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const a=1e3*t.start(s),r=1e3*t.end(s);a<=e&&e<=r&&(i=r)}return Math.max(i-e,0)};class Kt{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(t,e=[],i,s,a,r){this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=a,this._errorCb=r,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{if(p(this._xhr),this._xhr?.status>=400)return this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));this._headersCb?.(new Headers(e))}else 4===this._xhr.readyState?this._completeCb?.(this._xhr.response):3===this._xhr.readyState&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.('XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout((()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.('XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Zt{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(t){this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),e?.()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,a,r,n){this.abort((()=>{let o=0;const d=Date.now();let h=0,u=0,c=0;const l=t=>{s(Zt._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=dt(p)),this._lastXhr=new Kt(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),a?.()}),(t=>{if(t.length-o>n&&l(t),0===u)return void(u=Date.now());c=t.length-h;const e=Date.now()-u;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,h=t.length,u=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),r,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),t?.()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Zt._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class te{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(t){this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=t.onDashCallback??(()=>{}),this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},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(t),s='-'===i?.[1]?-1:1;e(i?.[2],s),e(i?.[3],s),e(i?.[4],s),e(i?.[5],s);return 3600*e(i?.[6],s)+60*e(i?.[7],s)+e(i?.[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=dt(i)),new Kt(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,a=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(a(s,'mediaPresentationDuration')));const r=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{const s=t.getElementsByTagName('SegmentBase')[0],o=s&&a(s,'indexRange').split('-'),d=s&&s.getElementsByTagName('Initialization')[0],h=d&&a(d,'range').split('-');if(!h||!o){const e=t.parentElement;if('text'===e?.getAttribute('contentType')){const s=t.getAttribute('id')??void 0,a=(i?i+'/':'')+t.getElementsByTagName('BaseURL')?.[0]?.childNodes?.[0]?.data,r=e.getAttribute('lang')??void 0;a&&n.push({id:s,url:a,language:r})}return}const u=Number(t.attributes.getNamedItem('bandwidth')?.value),c=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let l;const p=t.attributes.getNamedItem('frameRate')?.value??void 0;l=p?Et(p):void 0,r.push({width:Number(t.attributes.getNamedItem('width')?.value),height:Number(t.attributes.getNamedItem('height')?.value),bandwidth:u,baseURL:c,failoverHosts:e,indexFrom:Number(o[0]),indexTo:Number(o[1]),initFrom:Number(h[0]),initTo:Number(h[1]),codecs:t.attributes.getNamedItem('codecs')?.value??void 0,mimeType:t.attributes.getNamedItem('mimeType')?.value??void 0,fps:l,bufferSize:.1*u/8,bufferLength:.1,name:t.attributes.getNamedItem('okQuality')?.value??void 0,id:t.attributes.getNamedItem('id')?.value??void 0})})),r.length?(this._representations=r,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const a=new DataView(i.buffer);s+=12;const r=a.getUint32(s+4,!1);s+=8;let n=a.getUint32(s,!1),o=a.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=a.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&a.getUint32(s,!1)),i=n+a.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/r,toTime:i/r,fromOffset:o,toOffset:e-1}),o=e,n=i}const h=t.refs[t.refs.length-1];h.toTime-h.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,a;const r=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let r;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');r=e.to-this._video.currentTime,r<t.bufferLength&&(this._onDashCallback('buffering'),a!==e.to&&(a=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*r)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{r()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Zt({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const a=this._findRef(e);if(a){if(i){this._isLastRef(a)&&e>=a.toTime&&(e=a.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:a.fromTime}this._appendVector[String(a.fromTime)]=t,this._stream.load(t,a.fromOffset,a.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const a=.1;if(s.toTime<i.to+a){const e=this._findRef(s.toTime);e&&e.toTime<i.to+a?(this._buffer.smartRemove(s.fromTime-a,e.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-a,s.toTime+a,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!r(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){const e=this._currentRepresentation?.refs;if(!e)return;if(Array.isArray(e)&&0===e.length)return void this._params.onError('emptyrefs','Empty refs');let i;for(let s=0;s<e.length;s++){const a=e[s];if(a.fromTime<=t&&a.toTime>t)return a;a.fromTime>t&&(!i||a.fromTime<i.fromTime)&&(i=a)}if(!i){const i=e[e.length-1];if(t>i.toTime)return i}return i}_isLastRef(t){const e=this._currentRepresentation?.refs;if(!e)return!1;const i=e[e.length-1];return t.fromTime===i.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var ee;!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ee||(ee={}));const ie=[ee.PAUSED,ee.PLAYING];class se{videoState=new Y(ee.STOPPED);subscription=new i;video;buffer;dash;representations$=new t([]);currentRepresentation$=new t(void 0);params;textTracksManager=new ft;elementSize$=new t(void 0);dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e};log;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=gt(t.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new vt(this.video),this.dash=new te({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i,category:a.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',category:a.WTF,message:'DashProvider internal logic error',thrown:e})},o=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},h=Tt(this.video),p=(t,e)=>this.subscription.add(t.subscribe(e,i));p(h.timeUpdate$,t.position$),p(h.durationChange$,t.duration$),p(h.ended$,t.endedEvent$),p(h.looped$,t.loopedEvent$),p(h.error$,t.error$),p(h.isBuffering$,t.isBuffering$),p(h.playing$,t.firstFrameEvent$),p(h.canplay$,t.canplay$),this.subscription.add(h.seeking$.subscribe((()=>{r(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===ee.PLAYING||this.videoState.getState()===ee.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(h.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,h.volumeState$,i)),this.subscription.add(h.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,e.playbackRate,h.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),p(Ct(this.video),this.elementSize$),this.subscription.add(h.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)}),i)).add(h.pause$.subscribe((()=>{this.videoState.setState(ee.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)}))).add(h.playing$.subscribe((()=>{this.videoState.setState(ee.PLAYING),M(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(h.loadedMetadata$.subscribe((()=>{this.videoState.setState(ee.METADATA_LOADED)}),i)).add(h.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,category:a.WTF,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(d(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,n(this.video,'progress')).pipe(u((()=>{const t=this.currentRepresentation$.getValue(),e=this.representations$.getValue(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition(),a=this.params.desiredState.videoTrack.getState(),r=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),n=this.elementSize$.getValue(),d=o();let h;if(i&&this.params.desiredState.autoVideoTrackSwitching.setState(i.to),!d&&s(a))h=a;else{const i=Xt(this.video.buffered,1e3*this.video.currentTime),s=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,a=Math.min(i/s,1);h=_t(e.map((({track:t})=>t)),{container:n,throughput:r,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:a,playbackRate:this.video.playbackRate,current:e.find((({representation:e})=>e===t))?.track})?.id}return s(h)?e.find((({track:t})=>t.id===h))?.representation:void 0})),l()).subscribe(this.currentRepresentation$,i)).add(g({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(v((t=>t.to===ee.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(v(s))}).pipe(S()).subscribe((()=>this.videoState.setState(ee.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(v(s),l(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&o()?t.height<=e.height:t===e))).subscribe((t=>{const e=Xt(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!o())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(It(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Jt(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(S(),b(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(v(s)).subscribe(this.handleRepresentationPlay,i)).add(d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return o(t)}}handleManifestReady=t=>{const e=[];for(const i of t){const t=i.name??i.id??i.height.toString(10),s=(i.name&&Ot(i.name))??H(i),a=i.bandwidth/1e3,r={width:i.width,height:i.height},n=i.fps;if(!s)continue;const o={id:t,quality:s,bitrate:a,size:r,fps:n};e.push({track:o,representation:i})}this.representations$.next(e),this.params.output.availableVideoTracks$.next(e.map((({track:t})=>t))),this.videoState.setState(ee.MANIFEST_LOADED)};handleRepresentationPlay=t=>{const e=this.representations$.getValue().find((({representation:e})=>e===t))?.track;if(e){this.params.output.currentVideoTrack$.next(e);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(e.id)}};selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return p(t,'Can\'t select representation. something went wrong'),t};seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(ee.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i!==P.STOPPED){if(!e)switch(s?.to!==P.PAUSED&&a.state===C.Requested&&ie.includes(t)&&this.seek(a.position,a.forcePrecise),t){case ee.STOPPED:return this.videoState.startTransitionTo(ee.MANIFEST_LOADED),void this.prepare();case ee.MANIFEST_LOADED:return void this.videoState.startTransitionTo(ee.INITIAL_REPRESENTATION_SELECTED);case ee.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(ee.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case ee.METADATA_LOADED:return this.videoState.startTransitionTo(ee.READY),void this.dash.updateRefsForCurrentTime();case ee.READY:return void(i===P.PAUSED?(this.videoState.setState(ee.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()));case ee.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):s?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case ee.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):s?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}else t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0))}}var ae,re,ne,oe,de;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ae||(ae={})),function(t){t.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',t.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(re||(re={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(ne||(ne={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.PARTIALLY_EJECTED='partially_ejected',t.FED='fed'}(oe||(oe={})),function(t){t.MP4='mp4',t.WEBM='webm'}(de||(de={}));var he=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const ue='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;let ce=!1;try{ce=bt()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??'',10)<16}catch(t){console.error(t)}class le{bufferFull$=new e;error$=new e;buffer;queue=[];currentTask=null;destroyed=!1;constructor(t){this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}async append(t,e){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}async remove(t,e,i){return(!i||!i.aborted)&&new Promise((s=>{const a={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(a),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ce&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}completeTask=()=>{try{if(this.currentTask){const t=this.currentTask.signal?.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',category:a.VIDEO_PIPELINE,message:'Buffer appending or removal failed',thrown:t})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(t.signal?.aborted)return t.callback(!1),void this.pull();this.currentTask=t;const{operation:e}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===e?this.bufferFull$.next(this.currentTask.data.byteLength):t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===e||this.error$.next({id:`BufferTaskQueue:${e}`,category:a.VIDEO_PIPELINE,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:e}=t;switch(e){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(t.init);break;default:o(e)}}}var pe,me=t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pe||(pe={}));class fe{throughputEstimator;requestQuic;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);abortAllController=new et;subscription=new i;constructor({throughputEstimator:t,requestQuic:e}){this.throughputEstimator=t,this.requestQuic=e}onHeadersReceived(t){const{type:e,reused:i}=Jt(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest=E(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=dt(e));const i=yield tt(e,{signal:this.abortAllController.signal}).catch(ge);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=E(this.abortAllController.signal,async function*(t,{rangeMethod:e=pe.HEADER,range:i,onProgress:s,priority:a='auto',signal:r,measureThroughput:h=!0}={}){let u=t;const c=new Headers;if(i)switch(e){case pe.HEADER:c.append('Range',`${i.from}-${i.to}`);break;case pe.PARAM:{const t=new URL(u,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),u=t.toString();break}default:o(e)}this.requestQuic&&(u=dt(u));let l=this.abortAllController.signal;if(r){const t=new et;if(this.subscription.add(d(n(this.abortAllController.signal,'abort'),n(r,'abort')).subscribe((()=>{try{t.abort()}catch(t){ge(t)}}))),this.abortAllController.signal.aborted||r.aborted)try{t.abort()}catch(t){ge(t)}l=t.signal}const p=y(),m=yield tt(u,{priority:a,headers:c,signal:l}).catch(ge),f=y();if(this.throughputEstimator?.addRawRtt(f-p),!m)return null;if(!m.ok||!m.body)return Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));this.onHeadersReceived(m.headers);const g=parseInt(m.headers.get('Content-Length')??'',10)||i&&i.to-i.from+1||NaN;if(!g){const t=yield m.arrayBuffer();return this.throughputEstimator?.addRawSpeed(t.byteLength,y()-f),s?.(new DataView(t),t.byteLength),t}if(!s&&!h)return m.arrayBuffer();const[S,b]=m.body.tee(),v=S.getReader();h&&this.throughputEstimator?.trackStream(b);let T=0;const w=new ArrayBuffer(g),$=new Uint8Array(w),k=new DataView(w);let A=!1;const P=t=>{A=!0,ge(t)},R=E(l,async function*({done:t,value:e}){0===T&&this.lastRequestFirstBytes$.next(y()-p),l.aborted||(t?s?.(k,T):e&&($.set(e,T),T+=e.byteLength,s?.(k,T),yield v?.read().then(R,P)))}.bind(this));return yield v?.read().then(R,P),A?null:w}.bind(this));async fetchRepresentation(t,e,i='auto'){const{type:s}=t;switch(s){case ne.BYTE_RANGE:return await this.fetchByteRangeRepresentation(t,e,i)??null;case ne.TEMPLATE:return await this.fetchTemplateRepresentation(t,i)??null;default:o(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=E(this.abortAllController.signal,async function*(t,e,i){if(t.type!==ne.BYTE_RANGE)return null;const{from:s,to:a}=t.initRange;let r,n,o=s,d=a,h=!1;t.indexRange&&(r=t.indexRange.from,n=t.indexRange.to,h=a+1===r,h&&(o=Math.min(r,s),d=Math.max(n,a))),o=Math.min(o,0);const u=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!u)return null;const c=new DataView(u,s-o,a-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(h&&void 0!==r&&void 0!==n)p=new DataView(u,r-o,n-r+1);else{const s=e.getIndexRange(l);if(s){const e=yield this.fetch(t.url,{rangeMethod:pe.PARAM,range:s,priority:i,measureThroughput:!1});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const m=e.parseSegments(p,l);return{dataView:new DataView(u),segments:m}}.bind(this));fetchTemplateRepresentation=E(this.abortAllController.signal,async function*(t,e){if(t.type!==ne.TEMPLATE)return null;const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield this.fetch(i,{priority:e,measureThroughput:!1});if(!s)return null;return{segments:t.segments.map((t=>({...t,status:oe.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this))}const ge=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Se=new TextDecoder('ascii'),be=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),a=Se.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const r=Math.min(i,t.byteLength)-e;return{id:a,size:i,contents:new DataView(t.buffer,t.byteOffset+e,r)}},ve={validateData:t=>'ftyp'===Se.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=be(t),i=[];let s=0;const a=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&a()))throw new SyntaxError('Unsupported sidx version');a();const r=a(),n=a(),o=a(),d=4294967295&a();let h=n/r*1e3,u=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=a(),e=t>>>31,s=t<<1>>>1,n=a();if(a(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/r*1e3;i.push({status:oe.NONE,time:{from:h,to:h+o},byte:{from:u,to:u+s-1}}),h+=o,u+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const a=new DataView(t.buffer,t.byteOffset+e);try{const i=be(a);if(s||='mdat'===i.id,!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var ye,Te;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(ye||(ye={})),function(t){t.SignedInteger='int',t.UnsignedInteger='uint',t.Float='float',t.String='string',t.UTF8='utf8',t.Date='date',t.Master='master',t.Binary='binary'}(Te||(Te={}));const Ee={[ye.EBML]:{type:Te.Master},[ye.EBMLVersion]:{type:Te.UnsignedInteger},[ye.EBMLReadVersion]:{type:Te.UnsignedInteger},[ye.EBMLMaxIDLength]:{type:Te.UnsignedInteger},[ye.EBMLMaxSizeLength]:{type:Te.UnsignedInteger},[ye.DocType]:{type:Te.String},[ye.DocTypeVersion]:{type:Te.UnsignedInteger},[ye.DocTypeReadVersion]:{type:Te.UnsignedInteger},[ye.Void]:{type:Te.Binary},[ye.Segment]:{type:Te.Master},[ye.SeekHead]:{type:Te.Master},[ye.Seek]:{type:Te.Master},[ye.SeekID]:{type:Te.Binary},[ye.SeekPosition]:{type:Te.UnsignedInteger},[ye.Info]:{type:Te.Master},[ye.TimestampScale]:{type:Te.UnsignedInteger},[ye.Duration]:{type:Te.Float},[ye.Tracks]:{type:Te.Master},[ye.Chapters]:{type:Te.Master},[ye.Cluster]:{type:Te.Master},[ye.Timestamp]:{type:Te.UnsignedInteger},[ye.SilentTracks]:{type:Te.Master},[ye.SilentTrackNumber]:{type:Te.UnsignedInteger},[ye.Position]:{type:Te.UnsignedInteger},[ye.PrevSize]:{type:Te.UnsignedInteger},[ye.SimpleBlock]:{type:Te.Binary},[ye.BlockGroup]:{type:Te.Master},[ye.EncryptedBlock]:{type:Te.Binary},[ye.Attachments]:{type:Te.Master},[ye.Tags]:{type:Te.Master},[ye.Cues]:{type:Te.Master},[ye.CuePoint]:{type:Te.Master},[ye.CueTime]:{type:Te.UnsignedInteger},[ye.CueTrackPositions]:{type:Te.Master},[ye.CueTrack]:{type:Te.UnsignedInteger},[ye.CueClusterPosition]:{type:Te.UnsignedInteger},[ye.CueRelativePosition]:{type:Te.UnsignedInteger},[ye.CueDuration]:{type:Te.UnsignedInteger},[ye.CueBlockNumber]:{type:Te.UnsignedInteger},[ye.CueCodecState]:{type:Te.UnsignedInteger},[ye.CueReference]:{type:Te.Master},[ye.CueRefTime]:{type:Te.UnsignedInteger}},we=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=$e(t,i),a=s in Ee,r=a?Ee[s].type:Te.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),h=((n&255>>o)<<8*(o-1))+$e(d),u=i+o;let c;return c=u+h>t.byteLength?new DataView(t.buffer,t.byteOffset+u):new DataView(t.buffer,t.byteOffset+u,h),{tag:a?s:'0x'+s.toString(16).toUpperCase(),type:r,tagHeaderSize:u,tagSize:u+h,value:c,valueSize:h}},$e=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},ke=(t,e)=>{switch(e){case Te.SignedInteger:return t.getInt8(0);case Te.UnsignedInteger:return $e(t);case Te.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Te.String:return new TextDecoder('ascii').decode(t);case Te.UTF8:return new TextDecoder('utf-8').decode(t);case Te.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Te.Master:case Te.Binary:return t;default:o(e)}},Ae=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),a=we(s);if(!e(a))return;a.type===Te.Master&&Ae(a.value,e),i=a.value.byteOffset-t.byteOffset+a.valueSize}},Pe=[ye.Info,ye.SeekHead,ye.Tracks,ye.Chapters,ye.Cluster,ye.Cues,ye.Attachments,ye.Tags],Re=[ye.Timestamp,ye.SilentTracks,ye.SilentTrackNumber,ye.Position,ye.PrevSize,ye.SimpleBlock,ye.BlockGroup,ye.EncryptedBlock],De={validateData:t=>{if(t.getUint32(0)!==ye.EBML)return!1;let e,i,s;const a=we(t);return Ae(a.value,(({tag:t,type:a,value:r})=>(t===ye.EBMLReadVersion?e=ke(r,a):t===ye.DocType?i=ke(r,a):t===ye.DocTypeReadVersion&&(s=ke(r,a)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,a,r,n,o=!1,d=!1,h=!1;return Ae(t,(({tag:t,type:u,value:c,valueSize:l})=>{if(t===ye.SeekID){const t=ke(c,u);n=$e(t)}else t!==ye.SeekPosition&&(n=void 0);return t===ye.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===ye.Info?o=!0:t===ye.SeekHead?d=!0:t===ye.TimestampScale?s=ke(c,u):t===ye.Duration?a=ke(c,u):t===ye.SeekPosition&&n===ye.Cues?r=ke(c,u):o&&d&&Pe.includes(t)&&(h=!0),!h})),p(e,'Failed to parse webm Segment start'),p(i,'Failed to parse webm Segment end'),p(a,'Failed to parse webm Segment duration'),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:r}},getIndexRange:t=>{if(r(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,a=!1;const r=t=>s(t.time)&&s(t.position),n=[];let o;return Ae(t,(({tag:t,type:e,value:s})=>{switch(t){case ye.Cues:i=!0;break;case ye.CuePoint:o&&r(o)&&n.push(o),o={};break;case ye.CueTime:o&&(o.time=ke(s,e));break;case ye.CueTrackPositions:break;case ye.CueClusterPosition:o&&(o.position=ke(s,e));break;default:i&&Pe.includes(t)&&(a=!0)}return!(i&&a)})),o&&r(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:a}=t,r=n[i+1];return{status:oe.NONE,time:{from:s,to:r?r.time:e.segmentDuration},byte:{from:e.segmentStart+a,to:r?e.segmentStart+r.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Ae(t,(s=>s.tag===ye.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Re.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||=[ye.SimpleBlock,ye.BlockGroup,ye.EncryptedBlock].includes(s.tag)),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class _e{onLastSegment$=new t(!1);fullyBuffered$=new t(!1);playingRepresentation$=new t(void 0);error$=new e;gaps=[];subscription=new i;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new et;destroyAbortController=new et;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;constructor(t,e,i,s,{fetcher:a,tuning:r,getCurrentPosition:n}){switch(this.fetcher=a,this.tuning=r,this.forwardBufferTarget=r.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.container=i,i){case de.MP4:this.containerParser=ve;break;case de.WEBM:this.containerParser=De;break;default:o(i)}this.initData=new Map(s.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(s.map((t=>[t.id,t]))),this.kind=t,this.mediaSource=e,this.sourceBuffer=null}startWith=E(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);p(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new le(this.sourceBuffer),this.subscription.add(n(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',category:a.WTF,message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(n(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',category:a.VIDEO_PIPELINE,message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>{if(!this.sourceBuffer)return;const e=Math.min(this.bufferLimit,me(this.sourceBuffer.buffered));this.bufferLimit=e,this.pruneBuffer(t)}))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield this.loadInit(e,'high',!0);const i=this.initData.get(e.id),r=this.segments.get(e.id);if(p(i,'No init buffer for starting representation'),p(r,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let o=0;for(const t of r)t.time.from-o>0&&this.gaps.push({representation:e.id,from:o,to:t.time.from}),o=t.time.to;s(e.duration)&&e.duration-o>0&&this.gaps.push({representation:e.id,from:o,to:e.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=E(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const e=this.representations.get(t);p(e,`No such representation ${t}`);let i=this.initData.get(t);if(r(i)?yield this.loadInit(e,'high',!1):i instanceof Promise&&(yield i),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal);const a=this.getCurrentPosition();s(a)&&this.maintain(a)}.bind(this));abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(t){if(r(this.downloadingRepresentationId)||r(this.playingRepresentationId)||r(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(p(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let a=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=Xt(this.sourceBuffer.buffered,t),r=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(a=r)}if(isFinite(this.bufferLimit)&&me(this.sourceBuffer.buffered)>=.8*this.bufferLimit&&(this.pruneBuffer(1/0),s&&s.status!==oe.NONE))return;let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,e.segmentReference.type,a),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=n.at(0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===oe.FED&&!n.length&&Xt(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=i.at(-1);o&&o.status===oe.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){const e=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!e)return;const i=this.segments.get(e);if(!i)return;return i.find((e=>e.time.from<=t&&e.time.to>=t))?.time.from??void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){this.initData.clear(),this.segments.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&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===oe.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==ne.BYTE_RANGE)return t.slice(s,s+1);const a=t;let r=0;const n=[];for(let t=s;t<a.length&&r<=this.tuning.dash.segmentRequestSize;t++){const e=a[t];if(r+=e.byte.to+1-e.byte.from,e.status!==oe.NONE&&e.status!==oe.PARTIALLY_EJECTED)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,r,n=t;const{type:d}=e.segmentReference;switch(d){case ne.BYTE_RANGE:s=e.segmentReference.url,r={from:t.at(0).byte.from,to:t.at(-1).byte.to};break;case ne.TEMPLATE:{const i=t.at(0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),n=[i];break}default:o(d)}for(const t of n)t.status=oe.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:e.id});const{signal:h}=this.downloadAbortController;if(this.failedDownloads&&(await E(h,async function*(){const t=w(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),h.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:pe.PARAM,range:r,onProgress:(t,i)=>{if(!h.aborted)try{this.onSomeDataLoaded(t,e.id,r?r.from:0,i,h)}catch(t){this.error$.next({id:'SegmentFeeding',category:a.VIDEO_PIPELINE,message:'Error when feeding segments',thrown:t})}},signal:h,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}onSegmentDownloadError(t){let e=!1;const i=this.getCurrentPosition();if(this.sourceBuffer&&s(i)){e=Xt(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,e||this.error$.next({id:'SegmentDownload',category:a.NETWORK,message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,a){if(!this.activeSegments.size)return;const r=t=>{this.abortSegment(t.segment)},n=t=>{this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=oe.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const i of this.representations.values())if(i.id!==e)for(const e of this.segments.get(i.id)??[])e.status===oe.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=oe.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,h=t.byteLength;for(const o of this.activeSegments){const{segment:u}=o,c=d===ne.BYTE_RANGE,l=c?u.byte.to-u.byte.from+1:h;if(o.representationId!==e)continue;if(!(!c||u.byte.from>=i&&u.byte.to<i+t.byteLength))continue;if(a.aborted){r(o);continue}const p=c?u.byte.from-i:0,m=p<s,f=(c?u.byte.to-i:t.byteLength)<=s;if(u.status===oe.DOWNLOADING&&m&&f){u.status=oe.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,a).then((t=>t&&!a.aborted?n(o):r(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.feedingBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);i?.byteLength&&(u.status=oe.PARTIALLY_FED,o.feedingBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,a).then((t=>{if(a.aborted)r(o);else if(t)o.fedBytes+=i.byteLength,o.fedBytes===l&&n(o);else{if(o.feedingBytes<l)return;r(o)}})))}}}abortSegment(t){t.status===oe.PARTIALLY_FED||t.status===oe.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=oe.NONE)),t.status=oe.PARTIALLY_EJECTED):t.status=oe.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const a=s instanceof Promise;e||=a,null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=ue((()=>this.loadInit(i,'low',!1).finally((()=>this.initLoadIdleCallback=null)))))}async loadInit(t,e='auto',i=!1){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',r=(!i&&this.failedDownloads>0?E(this.destroyAbortController.signal,async function*(){const t=w(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s))).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,a),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',category:a.WTF,message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,r),r}async pruneBuffer(t){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||r(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,a=1/0,n=-1/0,o=!1;const d=t=>{a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const e='size'in t?t.size??0:t.byte.to-t.byte.from;s+=e};for(const a of i){if(a.time.to>=e||s>=t)break;a.status===oe.FED&&d(a)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const a of i){if(a.time.from<e+this.forwardBufferTarget||s>t)break;a.status===oe.FED&&d(a)}}if(o=isFinite(a)&&isFinite(n),!o)for(let t=0;t<this.sourceBuffer.buffered.length;t++){const e=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);for(const t of i)if(t.status===oe.NONE&&Math.round(t.time.from)<=Math.round(e)&&Math.round(t.time.to)>=Math.round(s)){a=e,n=s;break}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a,n)}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),e=t instanceof ArrayBuffer?t:void 0;this.sourceBufferTaskQueue.abort(e)}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),a=1e3*this.sourceBuffer.buffered.end(t);if(!(a<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&a>=i.time.to){e=void 0;break}a>i.time.from&&a<i.time.to&&(e.from=a),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ue((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',category:a.WTF,message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(r(this.sourceBuffer)||r(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=Math.round(1e3*this.sourceBuffer.buffered.start(e)),s=Math.round(1e3*this.sourceBuffer.buffered.end(e));t.push({from:i,to:s})}for(const e of this.segments.values())for(const i of e){const{status:e}=i;if(e!==oe.FED&&e!==oe.PARTIALLY_EJECTED)continue;const s=Math.floor(i.time.from),a=Math.ceil(i.time.to),r=t.some((t=>t.from-1<=s&&t.to+1>=a)),n=t.some((t=>s>=t.from-1&&s<=t.to+1||a>=t.from-1&&a<=t.to+1));r||(i.status=n?oe.PARTIALLY_EJECTED:oe.NONE)}}}const Ie=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},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(t),s='-'===i?.[1]?-1:1;return 24*e(i?.[5],s)*60*60*1e3+60*e(i?.[6],s)*60*1e3+60*e(i?.[7],s)*1e3+1e3*e(i?.[8],s)},Ce=(t,e)=>{let i=t;i=i.replaceAll('$$','$');const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[t,e]of Object.entries(s)){const s=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(s,((t,i)=>r(e)?t:r(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Le=['timeupdate','progress','play','seeked','stalled'];var xe,Ne;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(xe||(xe={}));class Be{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new i;fetcher;state$=new Y(xe.NONE);currentVideoRepresentation$=new t(void 0);error$=new e;lastConnectionType$=new t(void 0);lastConnectionReused$=new t(void 0);lastRequestFirstBytes$=new t(void 0);forceEnded$=new e;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new et;constructor(t){this.throughputEstimator=t.throughputEstimator,this.tuning=t.tuning,this.fetcher=new fe({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}initManifest=E(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(xe.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',category:a.NETWORK,message:'Failed to load manifest',thrown:t})));if(!i)return null;let r;try{r=((t,e)=>{const i={video:[],audio:[],text:[]},a=(new DOMParser).parseFromString(t,'application/xml').children[0],r=a.getElementsByTagName('Period')[0],n=r.children;let o;const d=a.getAttribute('mediaPresentationDuration'),h=r.getAttribute('duration');if(d)o=Ie(d);else if(h){const t=Ie(h);s(t)&&(o=t)}let u=0;const c=a.getAttribute('profiles')?.split(',')??[],l=c.includes(re.WEBM_AS_IN_FFMPEG)||c.includes(re.WEBM_AS_IN_SPEC)?de.WEBM:de.MP4;for(const t of n){const s=t.getAttribute('mimeType'),a=t.getAttribute('codecs'),r=t.getAttribute('contentType')??s?.split('/')[0],n=t.getAttribute('profiles')?.split(',')??[],d=t.querySelectorAll('Representation');if('text'!==r)for(const h of d){const d=h.getAttribute('mimeType')??s,l=h.getAttribute('codecs')??a??'',p=h.getAttribute('contentType')??d?.split('/')[0]??r,m=t.getAttribute('profiles')?.split(',')??[],f=parseInt(h.getAttribute('width')??'',10),g=parseInt(h.getAttribute('height')??'',10),S=parseInt(h.getAttribute('bandwidth')??'',10)/1e3,b=h.getAttribute('frameRate')??'',v=h.getAttribute('quality')??void 0,y=b?Et(b):void 0,T=`${h.getAttribute('id')??(u++).toString(10)}@${'video'===p?`${g}p`:'audio'===p?`${S}Kbps`:l}`,E=h.querySelector('BaseURL')?.textContent?.trim()??'',w=new URL(E,e).toString(),$=[...c,...n,...m];let k;const A=h.querySelector('SegmentBase'),P=h.querySelector('SegmentTemplate');if(A){const t=h.querySelector('SegmentBase Initialization')?.getAttribute('range')??'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},a=h.querySelector('SegmentBase')?.getAttribute('indexRange'),[r,n]=a?a.split('-').map((t=>parseInt(t,10))):[],o=a?{from:r,to:n}:void 0;k={type:ne.BYTE_RANGE,url:w,initRange:s,indexRange:o}}else{if(!P)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:h.getAttribute('id')??void 0,bandwidth:h.getAttribute('bandwidth')??void 0},e=parseInt(P.getAttribute('timescale')??'',10),i=P.getAttribute('initialization')??'',s=P.getAttribute('media'),a=parseInt(P.getAttribute('startNumber')??'',10)??1,r=Ce(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const n=P.querySelectorAll('SegmentTimeline S')??[],o=[];let d=a,u=0;for(const i of n){const a=1e3*parseInt(i.getAttribute('d')??'',10),r=parseInt(i.getAttribute('r')??'',10)||0,n=parseInt(i.getAttribute('t')??'',10)??void 0;for(let i=0;i<r+1;i++){const i=Ce(s,{...t,segmentNumber:d.toString(10),segmentTime:n.toString(10)}),r=n?n/e:u;u+=a/e;const h=u;d++,o.push({time:{from:r,to:h},url:i})}}k={type:ne.TEMPLATE,baseUrl:w,initUrl:r,segments:o}}}if(!p||!d)continue;const R={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[p];R&&i[R].push({id:T,kind:R,segmentReference:k,profiles:$,duration:o,bitrate:S,mime:d,codecs:l,width:f,height:g,fps:y,quality:v})}}return{duration:o,container:l,representations:i}})(i??'',e)}catch(t){this.error$.next({id:'ManifestParsing',category:a.PARSER,message:'Failed to parse MPD manifest',thrown:t})}if(!r)return null;const n=({mime:e,codecs:i})=>Boolean(t.canPlayType?.(e)&&window.MediaSource?.isTypeSupported?.(`${e}; codecs="${i}"`));return this.manifest={...r,representations:Object.fromEntries(Object.entries(r.representations).map((([t,e])=>[t,e.filter(n)])))},this.manifest.representations.video.length?this.state$.setState(xe.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',category:a.PARSER,message:'No playable video representations'}),this.manifest}.bind(this));initRepresentations=E(this.destroyController.signal,async function*(t,e){p(this.manifest),p(this.element),this.state$.startTransitionTo(xe.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new _e(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new _e(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const r=d(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),o=d(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(d(this.forceEnded$,g({allBuffersFull:r,someBufferEnded:o}).pipe(v((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{this.source?.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',category:a.VIDEO_PIPELINE,message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(d(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>this.source?.addEventListener('sourceopen',t)))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)]):yield this.videoBufferManager.startWith(t),this.state$.setState(xe.REPRESENTATION_SELECTED),p(this.element),this.subscription.add(d(...Le.map((t=>n(this.element,t))),n(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',category:a.WTF,message:'Internal logic error',thrown:t})}))),this.subscription.add(n(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(n(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&he(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this));async switchRepresentation(t,e){return{[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[t]?.switchTo(e)}seek(t,e){let i;p(this.element),p(this.videoBufferManager),i=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(this.videoBufferManager.findSegmentStartTime(t)??t,this.audioBufferManager?.findSegmentStartTime(t)??t),he(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=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(xe.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager?.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager?.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=$(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',category:a.WTF,message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=[];for(const i of this.bufferManagers)for(const s of i.gaps)i.playingRepresentation$.getValue()===s.representation&&s.from<=t&&s.to>t&&(1e3*this.element.duration-s.to<this.tuning.endGapTolerance?e.push(1/0):e.push(s.to));if(e.length){const t=Math.max(...e);t===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=t/1e3}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ne||(Ne={}));const Oe=({id:t,width:e,height:i,bitrate:s,fps:a,quality:r})=>{const n=(r?Ot(r):void 0)??H({width:e,height:i});return n&&{id:t,quality:n,bitrate:s,size:{width:e,height:i},fps:a}},Me=(t,e,i)=>{const s=e.indexOf(i);return t.at(Math.round(t.length*s/e.length))??t.at(-1)};class Ue{subscription=new i;videoState=new Y(Ne.STOPPED);video;player;params;elementSize$=new t(void 0);textTracksManager=new ft;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Dt;constructor(t){this.params=t,this.video=gt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(It(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Be({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=Tt(this.video),r=e=>{t.error$.next({id:'DashVKProvider',category:a.WTF,message:'DashVKProvider internal logic error',thrown:e})},o=(t,e)=>this.subscription.add(t.subscribe(e,r));o(i.timeUpdate$,t.position$),o(i.durationChange$,t.duration$),o(i.ended$,t.endedEvent$),o(i.looped$,t.loopedEvent$),o(i.error$,t.error$),o(i.isBuffering$,t.isBuffering$),o(i.currentBuffer$,t.currentBuffer$),o(i.playing$,t.firstFrameEvent$),o(i.canplay$,t.canplay$),o(this.player.error$,t.error$),o(this.player.lastConnectionType$,t.httpConnectionType$),o(this.player.lastConnectionReused$,t.httpConnectionReused$),o(this.player.lastRequestFirstBytes$.pipe(v(s),S(),b(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(ct(this.video,e.isLooped,r)),this.subscription.add(lt(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,e.playbackRate,i.playbackRateState$,r)),o(Ct(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Ne.PLAYING),M(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(Ne.PAUSED),M(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Ne.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(v((({to:t})=>t===xe.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Ne.READY)})));const h=e=>t.error$.next({id:'RepresentationSwitch',category:a.WTF,message:'Switching representations threw',thrown:e});this.subscription.add(d(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,n(this.video,'progress')).subscribe((()=>{const i=this.player.state$.getState(),s=this.player.state$.getTransition();if(i===xe.NONE||!this.videoTracks.length)return;const a=i===xe.MANIFEST_LOADED&&!s,r=i===xe.REPRESENTATION_SELECTED&&!s,n=e.autoVideoTrackSwitching.getState(),o=e.videoTrack.getState(),d=this.videoTracks.find((({track:{id:t}})=>t===o))?.track,u=t.currentVideoTrack$.getValue(),c=Xt(this.video.buffered,1e3*this.video.currentTime),l=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(c/Math.min(l,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),f=Math.max(d&&!n?this.audioRepresentations.get(d.id)?.bitrate??0:0,u?this.audioRepresentations.get(u.id)?.bitrate??0:0),g=_t(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:f,forwardBufferHealth:m,current:u,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=n?g??d:d??g;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(n),this.player.setBufferTarget(l)),a){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;p(t),this.player.initRepresentations(t.id,this.audioRepresentations.get(t.id)?.id)}else if(r){const t=S&&this.videoTracks.find((({track:t})=>t===S))?.representation;if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(ae.VIDEO,t.id).catch(h),e&&this.player.switchRepresentation(ae.AUDIO,e.id).catch(h)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(l(),u((t=>t&&this.videoTracks.find((({representation:{id:e}})=>e===t))?.track))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const f=d(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(f.subscribe(this.syncPlayback,r))}async prepare(){const t=await this.player.initManifest(this.video,this.params.source.url);if(!t)return;this.videoTracks=[];const e=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),i=Array.from(t.representations.video).sort(((t,e)=>e.bitrate-t.bitrate));for(const t of i){const s=Oe(t);if(s){this.videoTracks.push({track:s,representation:t});const a=Me(e,i,t);a&&this.audioRepresentations.set(t.id,a)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===C.Requested&&i?.to!==P.PAUSED&&t!==Ne.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===Ne.STOPPED)return this.videoState.startTransitionTo(Ne.READY),void this.prepare();switch(t){case Ne.READY:return void(e===P.PAUSED?(this.videoState.setState(Ne.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Ne.PLAYING),this.playIfAllowed()));case Ne.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Ne.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case Ne.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Ne.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}else t!==Ne.STOPPED&&(this.videoState.startTransitionTo(Ne.STOPPED),this.player.stop(),this.video.setAttribute('src',''),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ne.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0))};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Ne.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Ve={};var Fe;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Fe||(Fe={}));const qe=(t,e)=>new T((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class He{subscription=new i;videoState=new Y(Fe.INITIALIZING);video;params;hls;textTracksManager=new ft;trackLevels=new Map;constructor(t){this.video=gt(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(It(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',category:a.NETWORK,message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Ve.Hls=e.default,Ve.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){p(Ve.Hls,'hls.js not loaded'),this.hls=new Ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Fe.STOPPED)}subscribe(){p(Ve.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',category:a.WTF,message:'HlsJsProvider internal logic error',thrown:t})},n=Tt(this.video),o=(t,e)=>this.subscription.add(t.subscribe(e,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.currentBuffer$,e.currentBuffer$),o(n.loadStart$,e.firstBytesEvent$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.seeked$,e.seekedEvent$),this.subscription.add(ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,t.playbackRate,n.playbackRateState$,i)),this.subscription.add(qe(this.hls,Ve.Events.ERROR).subscribe((t=>{t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),category:a.WTF,message:`HlsJs fatal ${t.type} ${t.details}, ${t.err?.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(n.playing$.subscribe((()=>{this.videoState.setState(Fe.PLAYING),M(t.playbackState,P.PLAYING)}),i)).add(n.pause$.subscribe((()=>{this.videoState.setState(Fe.PAUSED),M(t.playbackState,P.PAUSED)}),i)).add(n.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Fe.READY&&this.videoState.setState(Fe.READY),this.videoState.getState()===Fe.PLAYING&&this.playIfAllowed()}),i)),o(qe(this.hls,Ve.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{const i=e.name||e.height.toString(10),{width:s,height:a}=e,r=Ot(e.attrs.QUALITY??'')??H({width:s,height:a});if(!r)return t;const n=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,o={id:i.toString(),quality:r,bitrate:e.bitrate/1e3,size:{width:s,height:a},fps:n};return this.trackLevels.set(i,{track:o,level:e}),t.push(o),t}),[])))),e.availableVideoTracks$),o(qe(this.hls,Ve.Events.LEVEL_LOADING).pipe(u((({url:t})=>It(t)))),e.hostname$),this.subscription.add(ut(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const h=t=>Array.from(this.trackLevels.values()).find((({level:e})=>e===t))?.track,l=qe(this.hls,Ve.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>h(this.hls.levels[t]))));l.pipe(v(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ut(t.videoTrack,(()=>h(this.hls.levels[this.hls.currentLevel])?.id),(t=>{if(r(t))return;const e=this.trackLevels.get(t)?.level;if(!e)return;const i=this.hls.levels.indexOf(e),s=this.hls.currentLevel,a=this.hls.levels[s];!a||e.bitrate>a.bitrate?this.hls.nextLevel=i:(this.hls.loadLevel=i,this.hls.loadLevel=i)}),{changed$:l.pipe(u((t=>t?.id))),onError:i})),o(n.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const f=d(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(f.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==Fe.INITIALIZING)switch(i?.to!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Fe.STOPPED:break;case Fe.READY:case Fe.PLAYING:case Fe.PAUSED:this.stop();break;default:o(t)}break;case P.PLAYING:switch(t){case Fe.PLAYING:break;case Fe.STOPPED:this.prepare();break;case Fe.READY:case Fe.PAUSED:this.playIfAllowed();break;default:o(t)}break;case P.PAUSED:switch(t){case Fe.PAUSED:break;case Fe.STOPPED:this.prepare();break;case Fe.READY:this.videoState.setState(Fe.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED);break;case Fe.PLAYING:this.pause();break;default:o(t)}break;default:o(e)}};prepare(){this.videoState.startTransitionTo(Fe.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Fe.PLAYING);await Mt(this.video)||(this.videoState.setState(Fe.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Fe.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/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.setAttribute('src',''),this.video.load(),this.videoState.setState(Fe.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)}}var Ge=async t=>{const e=await tt(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0};const Ye=t=>{let e=null;if(t.QUALITY&&(e=Ot(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=H({width:i,height:s})}return e??null},ze=async(t,e=t)=>{const i=await tt(t),s=(await i.text()).split('\n'),a=[];for(let t=0;t<s.length;t++){const i=s[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!i)continue;const r=Object.fromEntries(i[1].split(',').map((t=>t.split('=')))),n=r.QUALITY??`stream-${r.BANDWIDTH}`,o=Ye(r);let d;r.BANDWIDTH&&(d=parseInt(r.BANDWIDTH,10)/1e3||void 0),!d&&r['AVERAGE-BANDWIDTH']&&(d=parseInt(r['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=r['FRAME-RATE']?parseFloat(r['FRAME-RATE']):void 0;let u;if(r.RESOLUTION){const[t,e]=r.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(u={width:t,height:e})}const c=new URL(s[++t],e).toString();o&&a.push({id:n,quality:o,url:c,bandwidth:d,size:u,fps:h})}return a};var Qe,We,je;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Qe||(Qe={}));class Je{subscription=new i;videoState=new Y(Qe.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);maxSeekBackTime$;liveOffset=new St;manifestStartTime$=new t(void 0);constructor(e){this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),ze(O(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([i,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',category:a.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(It(this.params.source.url)),this.maxSeekBackTime$=new t(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',category:a.WTF,message:'HlsLiveProvider internal logic error',thrown:e})},r=Tt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.ended$,t.endedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadedMetadata$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Qe.PLAYING),M(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Qe.PAUSED),M(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===Qe.READY&&this.videoState.setState(Qe.READY),this.videoState.getState()===Qe.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(l(),u((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(It(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===Qe.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{const t=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(t||void 0)}),i)),this.subscription.add(g({startTime:this.manifestStartTime$.pipe(v(s)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,c(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(r(t))return;const e=O(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),Ge(e).then((t=>{if(r(t)){const t=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(r(t)||!isFinite(t))try{tt(e).then((t=>t.text())).then((t=>{const i=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(t)?.[1];if(i){const t=new URL(i,e).toString();Ge(t).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}}))}catch(t){}}else this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(Qe.PAUSED),this.liveOffset.pause(),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Qe.STOPPED&&(this.videoState.startTransitionTo(Qe.STOPPED),this.video.setAttribute('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(Qe.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===Qe.STOPPED)return this.videoState.startTransitionTo(Qe.READY),void this.prepare();if(s||a){const t=this.videoState.getState();return this.videoState.setState(Qe.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if(i?.to!==P.PAUSED&&r.state===C.Requested)return this.videoState.startTransitionTo(Qe.READY),this.seek(r.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Qe.READY:return void(e===P.PAUSED?(this.videoState.setState(Qe.PAUSED),this.liveOffset.pause(),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qe.PLAYING),this.playIfAllowed()));case Qe.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qe.PAUSED),this.liveOffset.pause(),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case Qe.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qe.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)):this.seek(-this.liveOffset.getTotalOffset())):i?.to===P.PAUSED&&(M(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Qe.CHANGING_MANIFEST:break;default:return o(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(We||(We={}));class Xe{subscription=new i;videoState=new Y(We.STOPPED);video;params;textTracksManager=new ft;manifests$=new t([]);constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video);const e={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([e]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(It(this.params.source.url)),ze(this.params.source.url).then((t=>{this.manifests$.next([e,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',category:a.NETWORK,message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:t,videoTrack:e}=this.params.desiredState,i=t.getState(),s=e.getTransition(),a=s?.to??e.getState()??'master',r=this.manifests$.getValue();if(!r)return;const n=i?'master':a;return i&&!s&&e.startTransitionTo('master'),r.find((t=>t.id===n))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',category:a.WTF,message:'HlsProvider internal logic error',thrown:e})},r=Tt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadedMetadata$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(We.PLAYING),M(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(We.PAUSED),M(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===We.READY&&this.videoState.setState(We.READY),this.videoState.getState()===We.PLAYING&&this.playIfAllowed()}),i).add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(It(e.url)))}a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),e&&e.from===We.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===C.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:a})=>({id:t,quality:e,size:i,fps:a,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const o=d(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();r(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(We.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==We.STOPPED&&(this.videoState.startTransitionTo(We.STOPPED),this.video.setAttribute('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(We.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.seekState.getState();if(t===We.STOPPED)return this.videoState.startTransitionTo(We.READY),void this.prepare();if(s||a){const t=this.videoState.getState();this.videoState.setState(We.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case We.READY:return void(e===P.PAUSED?(this.videoState.setState(We.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(We.PLAYING),this.playIfAllowed()));case We.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(We.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case We.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(We.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));case We.CHANGING_MANIFEST:break;default:return o(t)}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(je||(je={}));class Ke{subscription=new i;videoState=new Y(je.STOPPED);video;trackUrls={};params;textTracksManager=new ft;constructor(t){this.params=t,this.video=gt(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',category:a.WTF,message:'MpegProvider internal logic error',thrown:e})},r=Tt(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadedMetadata$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(je.PLAYING),M(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(je.PAUSED),M(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===je.READY&&this.videoState.setState(je.READY);const t=this.params.desiredState.videoTrack.getTransition();t&&s(t.to)&&(this.params.desiredState.videoTrack.setState(t.to),this.params.output.currentVideoTrack$.next(this.trackUrls[t.to].track)),this.videoState.getState()===je.PLAYING&&this.playIfAllowed()}),i)),this.textTracksManager.connect(this.video,e,t);const o=d(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();p(t,'MpegProvider: track is not selected');let{url:e}=this.trackUrls[t];p(e,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(e=dt(e)),this.video.setAttribute('src',e),this.video.load(),this.params.output.hostname$.next(It(e))}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(je.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==je.STOPPED&&(this.videoState.startTransitionTo(je.STOPPED),this.video.setAttribute('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(je.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(t===je.STOPPED)return this.videoState.startTransitionTo(je.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch(i?.to!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case je.READY:return void(e===P.PAUSED?(this.videoState.setState(je.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(je.PLAYING),this.playIfAllowed()));case je.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(je.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case je.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(je.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}}const Ze=['stun:videostun.mycdn.me:80'],ti=()=>null;class ei{options;ws=null;peerConnection=null;serverUrl='';streamKey='';stream=null;signalingType='JOIN';retryTimeout;retryCount=0;externalStartCallback=ti;externalStopCallback=ti;externalErrorCallback=ti;constructor(t,e){this.options=this.normalizeOptions(e);const i=t.split('/');this.serverUrl=i.slice(0,i.length-1).join('/'),this.streamKey=i[i.length-1]}onStart(t){try{this.externalStartCallback=t}catch(t){this.handleSystemError(t)}}onStop(t){try{this.externalStopCallback=t}catch(t){this.handleSystemError(t)}}onError(t){try{this.externalErrorCallback=t}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(t){this.handleSystemError(t)}}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(t){try{if(!this.ws)return;this.ws=null,t.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(t){try{this.externalErrorCallback(new Error(t.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(t){try{const e=this.parseMessage(t.data);switch(e.type){case'JOIN':case'CALL_JOIN':this.handleJoinMessage(e);break;case'UPDATE':this.handleUpdateMessage(e);break;case'STATUS':this.handleStatusMessage(e)}}catch(t){this.handleRTCError(t)}}handleJoinMessage(t){switch(t.inviteType){case'ANSWER':this.handleAnswer(t.sdp);break;case'CANDIDATE':this.handleCandidate(t.candidate)}}handleStatusMessage(t){switch(t.status){case'UNPUBLISHED':this.handleUnpublished()}}async handleUpdateMessage(t){try{const e=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(e),this.handleAnswer(t.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const t={iceServers:[{urls:Ze}]};this.peerConnection=new RTCPeerConnection(t),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const e=await this.createOffer();await this.peerConnection.setLocalDescription(e),this.send({type:this.signalingType,inviteType:'OFFER',streamKey:this.streamKey,sdp:e.sdp,callSupport:!1})}catch(t){this.handleRTCError(t)}}async handleAnswer(t){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:'answer',sdp:t}))}catch(t){this.handleRTCError(t)}}async handleCandidate(t){if(t)try{this.peerConnection&&await this.peerConnection.addIceCandidate(t)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(t){this.handleRTCError(t)}}handleSystemError(t){this.options.errorChanel&&this.options.errorChanel.next({id:'webrtc-provider-error',category:a.WTF,message:t.message})}async onPeerConnectionStream(t){const e=t.streams[0];this.stream&&this.stream.id===e.id||(this.stream=e,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(t){t.candidate&&this.send({type:this.signalingType,inviteType:'CANDIDATE',candidate:t.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const t=this.peerConnection.iceConnectionState;['failed','closed'].indexOf(t)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){if(!this.peerConnection)throw new Error('Can not create offer - no peer connection instance ');const t=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}),e=t.sdp||'';if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(e))throw new Error('No h264 codec support error');return t}handleRTCError(t){try{this.externalErrorCallback(t||new Error('RTC connection error'))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error('Network error'))}catch(t){this.handleSystemError(t)}}send(t){this.ws&&this.ws.send(JSON.stringify(t))}parseMessage(t){try{return JSON.parse(t)}catch(t){throw new Error('Can not parse socket message')}}closeConnections(){const t=this.ws;t&&(this.ws=null,t.close(1e3)),this.removePeerConnection()}removePeerConnection(){let t=this.peerConnection;t&&(this.peerConnection=null,t.close(),t.ontrack=null,t.onicecandidate=null,t.oniceconnectionstatechange=null,t=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),1e3)}normalizeOptions(t={}){const e={stunServerList:Ze,maxRetryNumber:3,errorChanel:null};return t.stunServerList&&(e.stunServerList=t.stunServerList),t.maxRetryNumber&&t.maxRetryNumber>0&&(e.maxRetryNumber=t.maxRetryNumber),e}}var ii;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(ii||(ii={}));class si{subscription;params;log;video;videoState=new Y(ii.STOPPED);liveStreamClient;maxSeekBackTime$=new t(0);constructor(t){this.subscription=new i,this.params=t,this.log=this.params.dependencies.logger.createComponentLog('WebRTCLiveProvider'),this.video=gt(t.container),this.liveStreamClient=new ei(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'WebRTCLiveProvider',category:a.WTF,message:'WebRTCLiveProvider internal logic error',thrown:e})};d(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})}));const s=Tt(this.video),r=(t,e)=>this.subscription.add(t.subscribe(e,i));r(s.timeUpdate$,t.liveTime$),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$),this.subscription.add(s.durationChange$.subscribe((e=>{t.duration$.next(e===1/0?0:e)}))).add(s.canplay$.subscribe((()=>{this.videoState.getTransition()?.to===ii.READY&&this.videoState.setState(ii.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(ii.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.videoState.setState(ii.PLAYING)}),i)).add(s.error$.subscribe(t.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(lt(this.video,e.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(t.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe((i=>{switch(i.to){case ii.STOPPED:t.position$.next(0),t.duration$.next(0),e.playbackState.setState(P.STOPPED);break;case ii.READY:break;case ii.PAUSED:e.playbackState.setState(P.PAUSED);break;case ii.PLAYING:e.playbackState.setState(P.PLAYING);break;default:return o(i.to)}}),i)).add(d(e.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,c(['init'])).pipe(m(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i))}onLiveStreamStart(t){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.hostname$.next(It(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:'webrtc',quality:B.INVARIANT}),this.video.srcObject=t,M(this.params.desiredState.playbackState,P.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ii.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(t){this.onLiveStreamStop(),this.params.output.error$.next({id:'WebRTC stream runtime error',category:a.EXTERNAL_API,message:t.message,thrown:t})}playIfAllowed(){Mt(this.video).then((t=>{t||(this.videoState.setState(ii.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED,!0))}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==ii.STOPPED&&(this.videoState.startTransitionTo(ii.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(ii.STOPPED),M(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition();if(t===ii.STOPPED)return this.videoState.startTransitionTo(ii.READY),void this.prepare();if(s)this.prepare();else switch(t){case ii.READY:return void(e===P.PAUSED?(this.videoState.setState(ii.PAUSED),M(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ii.PLAYING),this.playIfAllowed()));case ii.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ii.PAUSED),this.video.pause()):i?.to===P.PLAYING&&M(this.params.desiredState.playbackState,P.PLAYING));case ii.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ii.PLAYING),this.playIfAllowed()):i?.to===P.PAUSED&&M(this.params.desiredState.playbackState,P.PAUSED));default:return o(t)}}}class ai{iterator;current;constructor(t){this.iterator=t[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 Boolean(this.current.done)}}const ri=bt(),ni=navigator?.userAgentData?.mobile||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),oi=document.createElement('video'),di={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(oi.canPlayType?.('application/x-mpegurl')||oi.canPlayType?.('vnd.apple.mpegURL')),webrtc:Boolean(window.RTCPeerConnection)},hi={mp4:Boolean(oi.canPlayType?.('video/mp4')),webm:Boolean(oi.canPlayType?.('video/webm'))},ui={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},ci=(ui.h264||ui.h265)&&ui.aac,li=!ri,pi=di.hls&&hi.mp4&&(ni||ri),mi=Boolean(window.WebSocket);const fi=2e4,gi=3,Si={cacheDuration:12e4},bi={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},vi={maxPausedTime:3e4},yi={maxPausedTime:3e4};class Ti{current$=new t({type:void 0});providerError$=new e;noAvailableProvidersError$=new e;providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)};subscription=new i;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(t){this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:e}=this.params.tuning,i=e.length?[...t.screenFormatsPriority.filter((t=>!e.includes(t))),...t.screenFormatsPriority.filter((t=>e.includes(t)))]:t.screenFormatsPriority;this.screenFormatsIterator=new ai(((t,e=!1)=>t.filter((t=>{switch(t){case R.DASH:return di.mse&&hi.mp4&&ci&&li;case R.DASH_SEP:return di.mse&&hi.mp4&&ci;case R.DASH_WEBM:return di.mse&&hi.webm&&ui.vp9&&ui.opus;case R.DASH_LIVE:case R.DASH_ONDEMAND:return di.mse&&hi.mp4&&ci;case R.HLS:case R.HLS_LIVE:case R.HLS_ONDEMAND:return pi||e&&di.mse&&hi.mp4&&ci;case R.MPEG:return hi.mp4;case R.DASH_LIVE_WEBM:return!1;case R.WEB_RTC_LIVE:return di.webrtc&&mi&&ui.h264&&(hi.mp4||hi.webm);default:return o(t)}})))(i.filter((e=>s(t.sources[e]))),this.params.tuning.useHlsJs)),this.chromecastFormatsIterator=new ai(t.chromecastFormatsPriority.filter((e=>s(t.sources[e]))))}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 t=this.chooseDestination(),e=this.chooseFormat(t);if(r(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',category:a.WTF,message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const t=this.current$.getValue().destination;p(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case D.SCREEN:return this.createScreenProvider(e);case D.CHROMECAST:return this.createChromecastProvider(e);default:return o(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,a=this.providerOutput,r={container:i,source:null,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case R.DASH:{const i=this.applyFailoverHost(e[t]);return p(i),new se({...r,source:i,config:Si})}case R.DASH_SEP:case R.DASH_WEBM:case R.DASH_ONDEMAND:{const i=this.applyFailoverHost(e[t]);return p(i),this.params.tuning.useDashJs?new Bt({...r,source:i,format:t,config:yi}):new Ue({...r,source:i})}case R.HLS:case R.HLS_ONDEMAND:{const i=this.applyFailoverHost(e[t]);return p(i),pi||!this.params.tuning.useHlsJs?new Xe({...r,source:i}):new He({...r,source:i})}case R.HLS_LIVE:{const i=this.applyFailoverHost(e[t]);return p(i),new Je({...r,source:i,config:vi})}case R.MPEG:{const i=this.applyFailoverHost(e[t]);return p(i),new Ke({...r,source:i})}case R.DASH_LIVE:{const i=this.applyFailoverHost(e[t]);return p(i),new jt({...r,source:i,config:bi})}case R.WEB_RTC_LIVE:{const r=this.applyFailoverHost(e[t]);return p(r),new si({container:i,source:r,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case R.DASH_LIVE_WEBM:throw new Error('DASH_LIVE_WEBM is no longer supported');default:return o(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:a}=this.params,r=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return p(n),new Q({connection:n,meta:a,container:i,source:e,format:t,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?D.CHROMECAST:D.SCREEN}chooseFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case D.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return o(t)}}skipFormat(t){switch(t){case D.SCREEN:return this.screenFormatsIterator.next();case D.CHROMECAST:return this.chromecastFormatsIterator.next();default:return o(t)}}handleNoFormatsError(t){switch(t){case D.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case D.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return o(t)}}applyFailoverHost(t){if(void 0===this.failoverIndex)return t;const e=this.params.failoverHosts[this.failoverIndex];if(!e)return t;const i=t=>{const i=new URL(t);return i.host=e,i.toString()};if(void 0===t)return t;if('type'in t){if('raw'===t.type)return t;if('url'===t.type)return{...t,url:i(t.url)}}return Object.fromEntries(Object.entries(t).map((([t,e])=>[t,i(e)])))}initProviderErrorHandling(){const t=new i;let s=!1,r=0;var n;return t.add(d(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:fi,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(v((({type:t})=>void 0!==t)))},new T((t=>{const s=new i,a=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),r=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,c='unknown';return s.add(a.subscribe((t=>{h&&window.clearTimeout(h),c=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(r.subscribe((()=>{window.clearTimeout(h),c='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(c)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,category:a.WTF,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),t.add(this.current$.subscribe((()=>{s=!1;const e=this.params.desiredState.playbackState.transitionEnded$.pipe(v((({to:t})=>t===P.PLAYING)),S()).subscribe((()=>s=!0));t.add(e)}))),t.add(this.providerError$.subscribe((t=>{if(this.current$.getValue().destination===D.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>this.switchToNextProvider()),(()=>this.params.dependencies.chromecastInitializer.disconnect()));else{const e=t.category===a.NETWORK,i=this.params.failoverHosts.length>0&&(void 0===this.failoverIndex||this.failoverIndex<this.params.failoverHosts.length-1),n=r<gi;i&&(e&&s||!n)?(this.failoverIndex=void 0===this.failoverIndex?0:this.failoverIndex+1,this.reinitProvider()):n?(r++,this.reinitProvider()):this.switchToNextProvider()}}))),t}}const Ei=(t,e,i)=>i*e+(1-i)*t;class wi{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const i=e.label??'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Pt(`raw_${i}`),this.smoothedSeries$=new Pt(`smoothed_${i}`),this.reportedSeries$=new Pt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=(this.pastMeasures[t]-this.smoothed)**2,i++);e/=i;const s=Math.sqrt(e),a=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=Ei(this.slow,t,this.params.emaAlphaSlow),this.fast=Ei(this.fast,t,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>a||this.smoothed<n||(r(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 $i;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}($i||($i={}));const ki=new Map;let Ai=$i.RUNTIME;const Pi=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Pi,'test'),localStorage.removeItem(Pi),Ai=$i.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Pi),Ai=$i.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Ai=$i.RUNTIME}}})();const Ri=(t,e)=>{switch(Ai){case $i.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case $i.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case $i.RUNTIME:return void ki.set(t,e);default:o(Ai)}},Di=window.navigator.connection,_i=()=>{const t=Di?.downlink;if(s(t)&&10!==t)return 1e3*t},Ii=()=>{const t=Di?.rtt;if(s(t)&&3e3!==t)return t},Ci=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Li{throughput;rtt;subscription=new i;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const i=Li.load('one_video_throughput')||(e.useBrowserEstimation?_i():void 0)||5e3,a=Li.load('one_video_rtt')??(e.useBrowserEstimation?Ii():void 0)??0;if(this.throughput$=new t(i),this.rtt$=new t(a),this.rttAdjustedThroughput$=new t(Ci(i,a,e.rttPenaltyRequestSize)),this.throughput=new wi({initial:i,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new wi({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=_i();t&&this.throughput.next(t);const e=Ii();s(e)&&this.rtt.next(e)};Di&&'onchange'in Di&&this.subscription.add(n(Di,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Ri('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Ri('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(g({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>Ci(t,i,e.rttPenaltyRequestSize))),v((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let e=0,s=y();const a=new i;switch(this.subscription.add(a),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:a.add(n(t,'progress').pipe(S()).subscribe((t=>{e=t.loaded,s=y()})));break;case 1:case 0:a.add(n(t,'loadstart').subscribe((()=>{e=0,s=y()})))}a.add(n(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,a=y(),r=t-e,n=a-s;this.addRawSpeed(r,n,1)}this.concurrentDownloads.delete(t),a.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=y();let a=0,r=y();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:h})=>{d?(this.addRawSpeed(i,y()-s,1),this.concurrentDownloads.delete(t)):h&&(i+=h.byteLength,a+=h.byteLength,a>=this.tuningConfig.streamMinSampleSize&&y()-r>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,y()-r,this.concurrentDownloads.size),a=0,r=y()),await(e?.read().then(o,n)))};this.concurrentDownloads.add(t),e?.read().then(o,n)}addRawSpeed(t,e,i=1){if(Li.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){const e=(t=>{switch(Ai){case $i.LOCAL_STORAGE:return localStorage.getItem(t)??void 0;case $i.SESSION_STORAGE:return sessionStorage.getItem(t)??void 0;case $i.RUNTIME:return ki.get(t);default:o(Ai)}})(t);if(s(e))return parseInt(e,10)??void 0}}const xi={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}};const Ni=({playbackState:t,seekState:e,playbackAbort$:a,looped$:n,position$:o})=>new T((h=>{let c;const l=t.transitionEnded$.pipe(v((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=t.stateChangeEnded$.pipe(v((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=e.stateChangeEnded$.pipe(v((({to:e})=>e.state===C.Requested&&(t.getTransition()?.from??t.getState())===P.PLAYING))),f=e.stateChangeEnded$.pipe(v((({from:e,to:i})=>e.state===C.Applying&&i.state===C.None&&(t.getTransition()?.from??t.getState())===P.PLAYING))),g=d(l,f).pipe(u((()=>o.getValue())),v(s)),S=d(d(p,m,a),n).pipe(u((()=>o.getValue())),v(s));return(new i).add(g.subscribe((t=>{c=t}))).add(S.subscribe((t=>{if(r(c)||c===t)return;const e={from:c,to:t};c=void 0,h.next(e)})))})),Bi={[D.SCREEN]:{vod:[...pi?[R.HLS,R.HLS_ONDEMAND]:[],R.DASH_WEBM,R.DASH_SEP,R.DASH,R.DASH_ONDEMAND,...pi?[]:[R.HLS,R.HLS_ONDEMAND],R.MPEG],live:pi?[R.WEB_RTC_LIVE,R.HLS_LIVE,R.DASH_LIVE]:[R.WEB_RTC_LIVE,R.DASH_LIVE,R.HLS_LIVE]},[D.CHROMECAST]:{vod:[R.DASH_WEBM,R.DASH_SEP,R.DASH_ONDEMAND,R.HLS,R.HLS_ONDEMAND,R.MPEG],live:[R.HLS_LIVE]}};class Oi{subscription=new i;domContainer;providerContainer;chromecastInitializer;logger=new k;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new Y(P.STOPPED),seekState:new Y({state:C.None}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({})};info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentPlaybackRate$:new t(1),currentBuffer$:new t({start:0,end:0}),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(_.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)};events={inited$:new e,started$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,canplay$:new e,log$:new e};experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:kt};constructor(t={}){if(this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(xi)){const s=xi[i],a=t[i];Array.isArray(s)&&Array.isArray(a)?e[i]=a:e[i]='object'==typeof s&&'object'==typeof a?{...s,...a}:a??s}return e})(t),this.chromecastInitializer=new L({receiverApplicationId:t.chromecastReceiverId,isDisabled:t.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(e)}`,n=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,category:a.WTF,message:n,thrown:t}),t}}}})}initVideo(t){return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return p(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=t.meta?.videoId,this.providerContainer=new Ti({screenFormatsPriority:[...Bi[D.SCREEN].live,...Bi[D.SCREEN].vod],chromecastFormatsPriority:[...Bi[D.CHROMECAST].live,...Bi[D.CHROMECAST].vod],sources:t.sources,meta:t.meta??{},failoverHosts:t.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t,!1),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===_.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){p(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setPlaybackRate(t){p(this.providerContainer);const e=this.providerContainer?.providerOutput.element$.getValue();return e&&(this.desiredState.playbackRate.setState(t),e.playbackRate=t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){return(void 0===t||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t)))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){p(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(r(t))return this.info.position$.getValue();const e=this.desiredState.seekState.getState(),i=e.state===C.None?void 0:e.position;return s(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(d(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(v((()=>!this.isPlaybackStarted)),v((t=>t.to===P.PLAYING))).subscribe((()=>{this.isPlaybackStarted=!0,this.events.started$.next()}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=y(),this.events.inited$.next())}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===C.Requested?this.desiredState.seekState.setState({...t,state:C.Applying}):this.events.managedError$.next({id:`WillSeekIn${t.state}`,category:a.WTF,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),l()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>G(t)?1:G(e)?-1:V(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(t?.quality),this.info.videoBitrate$.next(t?.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(l()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(l()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(l()).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.currentBuffer$.pipe(u((t=>t?{start:t.from,end:t.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(u((t=>t.muted)),l()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),l()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>d(t.stateChangeEnded$.pipe(u((({to:t})=>t.state===C.None?void 0:(t.position??NaN)/1e3)),v(s)),e.pipe(v((()=>t.getState().state===C.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(d(e.providerOutput.endedEvent$.pipe(b(!0)),e.providerOutput.seekedEvent$.pipe(b(!1))).pipe(l()).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(u((t=>({id:'NoProviders',category:a.VIDEO_PIPELINE,message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(S(),u((()=>y()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(S(),u((()=>y()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(S(),u((()=>y()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const r=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>r.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>r.next(!0))));const o=new t(!0);this.subscription.add(e.current$.subscribe((()=>o.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(v((({to:t})=>t===P.PLAYING)),S()).subscribe((()=>o.next(!1))));let h=0;const c=d(e.providerOutput.isBuffering$,r,o).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=r.getValue()||o.getValue();return t&&!i})),l());this.subscription.add(c.subscribe((t=>{t?h=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(h),this.info.isStalled$.next(!1))})));const m=new i;this.subscription.add(m);const f=d(n(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(v((t=>Boolean(t?.provider)))));e.providerOutput.isLive$.pipe(l()).subscribe((e=>{switch(p(this.providerContainer),m.unsubscribe(),e){case!0:{const e=new t(void 0);m.add(this.providerContainer.providerOutput.liveTime$.subscribe((t=>e.next(t&&Math.floor(t/1e3))))),m.add(Ni({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:f,looped$:this.events.looped$,position$:e}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break}case!1:m.add(Ni({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:f,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(u((t=>t?.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(l(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(v((t=>t.length>0)),S()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=_t(t,{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})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(d(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const t=this.providerContainer?.providerOutput;p(this.providerContainer),p(t),$t={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{wt=t})),this.providerContainer.current$.subscribe((({type:t})=>At('provider',t))),t.duration$.subscribe((t=>At('duration',t))),t.availableVideoTracks$.pipe(v((t=>!!t.length)),S()).subscribe((t=>At('tracks',t))),this.events.fatalError$.subscribe(new Pt('fatalError')),this.events.managedError$.subscribe(new Pt('managedError')),t.position$.subscribe(new Pt('position')),t.currentVideoTrack$.pipe(u((t=>t?.quality))).subscribe(new Pt('quality')),this.info.currentBuffer$.subscribe(new Pt('buffer')),t.isBuffering$.subscribe(new Pt('isBuffering'))].forEach((t=>this.subscription.add(t))),At('codecs',Object.keys(ui).filter((t=>ui[t])))}}const Mi='@vkontakte/videoplayer-core@2.0.77';export{_ as ChromecastState,I as HttpConnectionType,P as PlaybackState,Oi as Player,Mi as SDK_VERSION,R as VideoFormat,B as VideoQuality};
|
|
6
|
+
import{ValueSubject as g,Subject as D,Subscription as K,isNonNullable as $,ErrorCategory as _,isNullable as z,fromEvent as M,assertNever as N,merge as O,tap as rs,map as v,observableFrom as ke,filterChanged as he,assertNonNullable as A,debounce as Ie,timeout as Ks,combine as qe,once as pe,mapTo as nt,filter as U,now as ce,Observable as _t,abortable as _e,getExponentialDelay as as,interval as Xs,Logger as Zs}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as na,Subject as oa,Subscription as da,ValueSubject as ca}from"@vkontakte/videoplayer-shared/esnext.esm.js";import ei from"lodash/debounce.js";const ti="2.0.78",si="@vkontakte/videoplayer-core";var f;(function(r){r.STOPPED="stopped",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var b;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var $e;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})($e||($e={}));var Te;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Te||(Te={}));var Dt;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(Dt||(Dt={}));var B;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(B||(B={}));var ii=r=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",r),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class ri{connection$=new g(void 0);castState$=new g(Te.NOT_AVAILABLE);errorEvent$=new D;contentId;realCastState$=new g(Te.NOT_AVAILABLE);subscription=new K;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 s=$(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},i||ii("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.NETWORK,message:"Script loading failed!"})))}connect(){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(){$(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();z(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();z(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(M(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=s.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 N(i.sessionState)}})).add(O(M(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rs(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),v(i=>i.castState)),ke([s.getCastState()])).pipe(he(),v(ai),rs(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const a=i===Te.CONNECTED,n=$(this.connection$.getValue());if(a&&!n){const o=s.getCurrentSession();A(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(z(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i===Te.CONNECTED?$(this.connection$.getValue())?Te.CONNECTED:Te.AVAILABLE:i)}))}initializeCastApi(){let e,t,s;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(i){this.errorEvent$.next({id:"ChromecastInitializer",category:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const ai=r=>{switch(r){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Te.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Te.AVAILABLE;case cast.framework.CastState.CONNECTING:return Te.CONNECTING;case cast.framework.CastState.CONNECTED:return Te.CONNECTED;default:return N(r)}};var ht;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ht||(ht={}));var ft=(r,e=0,t=ht.OFFSET_P)=>{switch(t){case ht.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ht.PLAYBACK_SHIFT:{if(e===0)return r;const s=new URL(r);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:N(t)}return r},w=(r,e,t=!1)=>{const s=r.getTransition();(t||!s||s.to===e)&&r.setState(e)},te;(function(r){r.INVARIANT="Invariant quality",r.Q_144P="144p",r.Q_240P="240p",r.Q_360P="360p",r.Q_480P="480p",r.Q_720P="720p",r.Q_1080P="1080p",r.Q_1440P="1440p",r.Q_2160P="2160p",r.Q_4320P="4320p"})(te||(te={}));const Ce={[te.Q_144P]:{width:256,height:144},[te.Q_240P]:{width:428,height:240},[te.Q_360P]:{width:640,height:360},[te.Q_480P]:{width:856,height:480},[te.Q_720P]:{width:1280,height:720},[te.Q_1080P]:{width:1920,height:1080},[te.Q_1440P]:{width:2560,height:1440},[te.Q_2160P]:{width:3840,height:2160},[te.Q_4320P]:{width:7680,height:4320}},Ut=(r,e)=>Ce[r].height>Ce[e].height,ni=(r,e)=>Ce[r].height>=Ce[e].height,At=(r,e)=>Ce[r].height<Ce[e].height,oi=(r,e)=>Ce[r].height<=Ce[e].height,di=r=>r.sort((e,t)=>e===t?0:e===te.INVARIANT?1:t===te.INVARIANT?-1:At(e,t)?1:-1)[0],ci=Object.keys(Ce).sort((r,e)=>At(r,e)?-1:1),ot=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return ci.find(i=>{const a=Ce[i];return a.width>=s&&a.height>=t})},ui=r=>Ce[r].height,Vt=r=>r===te.INVARIANT;class ae{state;transition;transitionStarted$=new D;transitionEnded$=new D;transitionUpdated$=new D;forceChanged$=new D;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||$(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const hi=r=>{switch(r){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.HLS_LIVE:case b.DASH_LIVE:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return N(r)}};var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));const li=5,fi=5,pi=500,ns=7e3;class mi{subscription=new K;loadMediaTimeoutSubscription=new K;videoState=new ae(G.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(hi(e.format)),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 K;this.subscription.add(e),this.subscription.add(O(this.videoState.stateChangeStarted$.pipe(v(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(v(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));const t=(i,a)=>this.subscription.add(i.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new D;e.add(i.pipe(Ie(pi)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(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===B.Applying||Math.abs(o-a)>li)&&i.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);const{remotePlayer:a}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),c=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==c&&this.params.output.isBuffering$.next(c),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<fi&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,f.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:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});const s=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,f.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===G.PAUSED||e===G.PLAYING)&&(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===G.PLAYING||e===G.PAUSED)&&(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)}handleRemoteStop(){this.videoState.getState()!==G.STOPPED&&this.videoState.setState(G.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};(s.volume!==t.volume||s.muted!==s.muted)&&this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let s,i,a;switch(e){case b.MPEG:{const d=t[e];A(d);const u=di(Object.keys(d));A(u);const h=d[u];A(h),s=h,i="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const d=t[e];A(d),s=d.url,i="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const d=t[e];A(d),s=d.url,i="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS_LIVE:{const d=t[e];A(d),s=ft(d.url),i="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",u=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:d,thrown:u}),u}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,i);n.contentUrl=s,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return $(o)&&(n.metadata.title=o),$(c)&&(n.metadata.subtitle=c),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===B.Applying||s.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((i,a)=>{this.loadMediaTimeoutSubscription.add(Ks(ns).subscribe(()=>a(`timeout(${ns})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,thrown:i})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),s===f.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.stop());return}if(!t){if(i?.to!==f.PAUSED&&a.state===B.Requested&&e!==G.STOPPED){this.seek(a.position);return}switch(s){case f.PLAYING:{switch(e){case G.PLAYING:break;case G.PAUSED:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.READY:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case G.PLAYING:this.videoState.startTransitionTo(G.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case G.PAUSED:break;case G.READY:this.videoState.startTransitionTo(G.PAUSED),this.videoState.setState(G.PAUSED);break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:N(e)}break}default:N(s)}}}}class os{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let i=0,a=s.length;i<a;i++)if(s[i].callback===t){s.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let i=0,a=s.length;i<a;i++){const n=s[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Is extends os{constructor(){super(),this.listeners||os.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Cs=class{constructor(){Object.defineProperty(this,"signal",{value:new Is,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Cs.prototype[Symbol.toStringTag]="AbortController",Is.prototype[Symbol.toStringTag]="AbortSignal");function Ls(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Si(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=r;if(!Ls({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||i)&&(a=function(d,u){let h;u&&u.signal&&(h=u.signal,delete u.signal);const l=new t(d,u);return h&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),l},a.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const u=a&&a.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(u){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(u.aborted)return Promise.reject(h);const l=new Promise((p,S)=>{u.addEventListener("abort",()=>S(h),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([l,n(c,d)])}return n(c,d)},Request:a}}const Qt=Ls({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xs=Qt?Si({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,pt=Qt?xs.fetch:window.fetch;Qt?xs.Request:window.Request;const rt=Qt?Cs:window.AbortController,Et=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class wt{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[a,n]=Et(i.request);if(a>=s.from&&n<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const i=this.sendBigRequest(e,t.map(({request:a})=>a));this.activeRequests.set(e,i)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),i=this.activeRequests.get(t.url);s&&i&&i.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(Et),i=s[0][0];let a=s[0][1];for(let l=1;l<s.length&&a<this.params.minDataSize;l++){const p=s[l][1];p-i<=2*this.params.minDataSize&&(a=Math.max(a,p))}i===0?a=Math.max(a,i+this.params.minInitSize):a=Math.max(a,i+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${i}-${a}`);const o=n.toString(),c=new rt,d=c.signal,u={url:e,from:i,to:a,loaded:0,data:null,abortController:c};d.addEventListener("abort",()=>this.onBigRequestAbort(u));const h=l=>{throw this.params.onError?.({id:"BigRequestParsing",category:_.PARSER,message:"Error parsing response data",thrown:l}),l};return pt(o,{signal:d}).then(l=>{if(u.response=l,!l.ok||!l.body){this.onBigRequestError(u);return}const[p,S]=l.body.tee();this.params.onDownloadStream?.(S);const m=p.getReader(),T=parseInt(l.headers.get("Content-Length")??"",10)||a-i+1;u.data=new ArrayBuffer(T);const P=new Uint8Array(u.data),L=async({done:se,value:k})=>{se?this.onBigRequestProgress(u):k&&(P.set(k,u.loaded),u.loaded+=k.byteLength,this.onBigRequestProgress(u),await m?.read().then(L,wt.suppressStreamErrors).catch(h))};m?.read().then(L,wt.suppressStreamErrors).catch(h)},wt.suppressAbort).catch(l=>this.onBigRequestError(u,l)),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a,response:n}){if(!this.activeRequests.has(e)||!a)return;const o=this.dashJsRequestQueue.get(e)??[];for(const c of o){const{request:d}=c,[u,h]=Et(d),l=u>=t&&h<=t+i,p=t>=u&&t+i<h,S=a.slice(u-t,Math.min(h-t+1,i));if((l||p)&&(d.requestStartDate=d.requestStartDate??new Date,d.firstByteDate=d.firstByteDate??new Date,d.bytesLoaded=S.byteLength,d.bytesTotal=s-t),l){d.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(T=>T!==c)),c.success?.(S,"",e);const m=n?Array.from(n.headers.entries()).map(([T,P])=>`${T}: ${P}`).join(`\r
|
|
7
|
+
`):"";this.dashMetrics?.addHttpRequest(d,e,n?.status??200,m,[])}else p&&c.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:"BigRequest",category:_.NETWORK,message:"Download error",thrown:i}),!this.activeRequests.has(e))return;const a=this.dashJsRequestQueue.get(e)??[];for(const n of a){const[o,c]=Et(n.request);(o>=t&&o<s||c>t&&c<=s)&&n?.error?.(n.request,String(i))}if(this.activeRequests.delete(e),i)throw i}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const i=this.dashJsRequestQueue.get(e)??[];for(const a of i){const[n,o]=Et(a.request);(n>=t&&n<s||o>t&&o<=s)&&a?.abort?.(a.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ht{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ht.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Ht.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const gi=(r,e)=>t=>({create:s=>{const i=r(t).create(s);return new Ht(i,e,s)}}),bi=(r,e)=>{const t=new wt(e);return r.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:a=>{const n=i(a);return gi(n,t)}}},!0),()=>t.destroy()};var yi=r=>{let e,t=!1,s=!1;r.on("playbackTimeUpdated",({timeToEnd:i})=>{s=i<=3,t&&s&&e?.()}),r.extend("MediaSourceController",function(){const{parent:i}=this,a=i.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&e?.()}}},!0)},Ti=r=>{const e=new g(1/0),t=new D,s=new g(void 0),i=new g(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},c=u=>{const h=Object.fromEntries(u.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const S=parseInt(u.getResponseHeader("X-Playback-Duration")??"",10),T=parseInt(u.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;$(T)&&!isNaN(T)&&e.next(T)}const l=h["x-delivery-type"]??Dt.HTTP1,p={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(l),i.next(p)},d=u=>{u.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return r.extend("XHRLoader",function(){const{parent:u}=this,h=u.load.bind(u);return{load:function(l){if(l.request.type==="MPD"){const p=l.onload,S=l.progress;l.onload=function(...m){return c(this),p(...m)},l.progress=function(...m){return d(this),S(...m)},o()}return h(l)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},mt=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Ei=r=>r.extend("RequestModifier",()=>({modifyRequestURL:mt}),!0),vi=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[i,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${i}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Be=(r,e,t,{equal:s=(n,o)=>n===o,changed$:i,onError:a}={})=>{const n=r.getState(),o=e(),c=z(i),d=new K;return i&&d.add(i.subscribe(u=>{const h=r.getState();s(u,h)&&r.setState(u)},a)),s(o,n)||(t(n),c&&r.setState(n)),d.add(r.stateChangeStarted$.subscribe(u=>{t(u.to),c&&r.setState(u.to)},a)),d},dt=(r,e,t)=>Be(e,()=>r.loop,s=>{$(s)&&(r.loop=s)},{onError:t}),Ge=(r,e,t,s)=>Be(e,()=>({muted:r.muted,volume:r.volume}),i=>{$(i)&&(r.muted=i.muted,r.volume=i.volume)},{equal:(i,a)=>i===a||i?.muted===a?.muted&&i?.volume===a?.volume,changed$:t,onError:s}),et=(r,e,t,s)=>Be(e,()=>r.playbackRate,i=>{$(i)&&(r.playbackRate=i)},{changed$:t,onError:s}),$i=r=>["__",r.language,r.label].join("|"),ki=(r,e)=>{if(r.id===e)return!0;const[t,s,i]=e.split("|");return r.language===s&&r.label===i};class Oe{available$=new D;current$=new g(void 0);error$=new D;video;cueSettings;subscription=new K;externalTracks=new Map;connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const i=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Be(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{$(a)&&this.setExternal(a)},{equal:(a,n)=>$(a)&&$(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(v(a=>a.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Be(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:i})),this.subscription.add(Be(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){A(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(O(M(e,"addtrack"),M(e,"removetrack"),ke(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),he((s,i)=>s.length===i.length&&s.every(({id:a},n)=>a===i[n].id))).subscribe(this.available$)),this.subscription.add(O(M(e,"change"),ke(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),v(s=>s&&this.htmlTextTrackToITextTrack(s).id),he()).subscribe(this.current$));const t=s=>this.applyCueSettings(s.target?.activeCues??null);this.subscription.add(M(e,"addtrack").subscribe(s=>{s.track?.addEventListener("cuechange",t);const i=a=>{const n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",i))};s.track?.addEventListener("cuechange",i)})),this.subscription.add(M(e,"removetrack").subscribe(s=>{s.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const i=s;$(t.align)&&(i.align=t.align),$(t.position)&&(i.position=t.position),$(t.size)&&(i.size=t.size),$(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){A(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=e.id!==""?e.id:$i(e);return this.externalTracks.has(i)?{id:i,type:"external",language:t,label:s,url:this.externalTracks.get(i).url}:{id:i,type:"internal",language:t,label:s}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){A(this.video);for(const t of this.htmlTextTracksAsArray(!0))$(e)&&ki(t,e)?t.mode="showing":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){A(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),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){A(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ye=r=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r.appendChild(e),e};class es{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Ns=()=>{const{userAgent:r}=window.navigator;return!/chrome/i.test(r)&&/webkit|safari|khtml/i.test(r)};const Zt=3;class Ai{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let i=this._source.buffered.start(t);const a=this._source.buffered.end(t);i>e&&i-e<Zt&&(i=e),this._buffer.push({from:i,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||Zt))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:i,to:a})=>{const n=i>=e&&i<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(i,e):i<e&&a>t?(s(t,a),s(i,e)):s(i,a))})}destroy(){this._buffer=[]}}var Bs=(r,e,t=Zt)=>{let s=0,i=0;for(let a=0;a<r.length;a++){const n=r.start(a),o=r.end(a);if(n<=e&&e<=o){if(s=n,i=o,!t)return{from:s,to:i};for(let c=a-1;c>=0;c--)r.end(c)+t>=s&&(s=r.start(c));for(let c=a+1;c<r.length;c++)r.start(c)-t<=i&&(i=r.end(c))}}return{from:s,to:i}};const ze=r=>{const e=p=>M(r,p).pipe(nt(void 0)),s=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(p=>M(r,p))).pipe(v(p=>p.type==="ended"?r.readyState<2:r.readyState<3),he()),i=O(M(r,"progress"),M(r,"timeupdate")).pipe(v(()=>Bs(r.buffered,r.currentTime))),a=Ns()?qe({play:e("play").pipe(pe()),playing:e("playing")}).pipe(nt(void 0)):e("playing"),n=M(r,"volumechange").pipe(v(()=>({muted:r.muted,volume:r.volume}))),o=M(r,"ratechange").pipe(v(()=>r.playbackRate)),c=M(r,"error").pipe(U(()=>Boolean(r.error||r.played.length)),v(()=>{const p=r.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:r.error??void 0}})),d=M(r,"timeupdate").pipe(v(()=>r.currentTime)),u=new D,h=.3;let l;return d.subscribe(p=>{r.loop&&$(l)&&$(p)&&l>=r.duration-h&&p<=h&&u.next(l),l=p}),{playing$:a,pause$:e("pause").pipe(U(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:M(r,"durationchange").pipe(v(()=>r.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:n,playbackRateState$:o}},ts=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let ss=!1,Ve={};const wi=r=>{ss=r},Pi=()=>{Ve={}},Ri=r=>{r(Ve)},Nt=(r,e)=>{ss&&(Ve.meta=Ve.meta??{},Ve.meta[r]=e)};class Ne{name;constructor(e){this.name=e}next(e){if(!ss)return;Ve.series=Ve.series??{};const t=Ve.series[this.name]??[];t.push([Date.now(),e]),Ve.series[this.name]=t}}const Di=new Ne("best_bitrate"),_i=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class Ii{last;history={};recordSelection(e){this.history[e.id]=ce()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const It=(r,{container:e,throughput:t,tuning:s,limits:i,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d})=>{const u=s.usePixelRatio?window.devicePixelRatio??1:1,h=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*u*s.containerSizeFactor,height:e.height*u*s.containerSizeFactor},l=h&&ot(h),p=s.considerPlaybackRate&&$(o)?o:1,S=r.filter(x=>!Vt(x.quality)).sort((x,ie)=>Ut(x.quality,ie.quality)?-1:1),m=S.at(-1)?.quality,T=S.at(0)?.quality,P=z(i)||$(i.min)&&$(i.max)&&At(i.max,i.min)||$(i.min)&&T&&Ut(i.min,T)||$(i.max)&&m&&At(i.max,m),L=p*_i(n??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),k=S.filter(x=>{const ie=l?At(x.quality,l):!0,V=$(t)&&isFinite(t)&&$(x.bitrate)?t-a>=x.bitrate*L:!0,j=s.lazyQualitySwitch&&$(s.minBufferToSwitchUp)&&c&&!Vt(c.quality)&&(n??0)<s.minBufferToSwitchUp&&Ut(x.quality,c.quality),ne=P||(z(i.max)||oi(x.quality,i.max))&&(z(i.min)||ni(x.quality,i.min));return ie&&V&&!j&&ne})[0];k&&k.bitrate&&Di.next(k.bitrate);const E=k??S[Math.ceil((S.length-1)/2)]??r[0],I=E&&d&&d.history[E.id]&&ce()-d.history[E.id]<=s.trackCooldown&&(!d.last||E.id!==d.last.id);if(E?.id&&d&&!I&&d.recordSelection(E),I&&d?.last){const x=d.last;return d?.recordSwitch(x),x}return d?.recordSwitch(E),E};var ve=r=>new URL(r).hostname;const Ci=300,qt=(r,e=Ci)=>new _t(t=>{const{width:s,height:i}=r.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const a=new ResizeObserver(ei(n=>{const o=n[0];if(!o)return;let c,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,c=o.contentBoxSize[0].inlineSize):o.contentRect&&(c=o.contentRect.width,d=o.contentRect.height),$(c)&&$(d)&&t.next({width:c,height:d})},e));return a.observe(r),()=>a.disconnect()}),Li=5e3,vt={};var Y;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Y||(Y={}));const fe=(r,e)=>new _t(t=>{const s=i=>t.next(i);return r.on(e,s),()=>r.off(e,s)});class xi{subscription=new K;videoState=new ae(Y.DOWNLOADING_LIB);video;player;params;textTracksManager=new Oe;videoTracks=[];frameRatesByFrameHeight={};isLive$=new g(void 0);maxSeekBackTime$=new g(1/0);availableFrom$=new g(void 0);elementSize$=new g(void 0);liveOffset=new es;destroyBigRequest;constructor(e){this.video=Ye(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:_.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Li);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(vt.MediaPlayer=i.MediaPlayer,vt.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){A(vt.MediaPlayer,"dashjs not loaded"),A(vt.Debug,"dashjs not loaded"),this.player=vt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?ts(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=bi(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&vi(this.player),yi(this.player),this.params.tuning.requestQuick&&Ei(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=m=>{e.error$.next({id:"DashIFProvider",category:_.WTF,message:"DashIFProvider internal logic error",thrown:m})},i=(m,T)=>this.subscription.add(m.subscribe(T,s));i(qt(this.video),this.elementSize$),i(fe(this.player,"error").pipe(v(m=>{const T=typeof m.error=="object"?m.error.code:m.error,P=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${T}`,message:P}})),e.error$),i(fe(this.player,"playbackError").pipe(v(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=fe(this.player,"qualityChangeRendered").pipe(U(({mediaType:m})=>m==="video"),v(({newQuality:m})=>this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===m)?.track));a.pipe(U($)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(U(({to:m})=>m===Y.STREAM_INITIALIZED),pe()).subscribe(()=>{this.subscription.add(Be(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===m)?.track?.id},m=>{if(z(m))return;const T=this.videoTracks.find(({track:P})=>P.id===m)?.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:a.pipe(v(m=>m?.id)),onError:s}))},s)),this.subscription.add(Be(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:s})),i(fe(this.player,"bufferStateChanged").pipe(U(({mediaType:m})=>m==="video"),v(({state:m})=>m==="bufferStalled")),e.isBuffering$),i(fe(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:T}})=>{const P=this.player.getDashMetrics(),L=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),se=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??Dt.HTTP1,k={1:!0,0:!1}[L]??void 0;this.params.output.httpConnectionType$.next(se),this.params.output.httpConnectionReused$.next(k),e.hostname$.next(ve(T))}),i(fe(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:T,availableFrom:P}}})=>{this.isLive$.next(T),this.availableFrom$.next(P.getTime()),T||e.duration$.next(m),this.videoTracks=[];const L=this.player.getQualityFor("video");let se;for(const k of this.player.getBitrateInfoListFor("video")){const E=k.qualityIndex.toString(10),I=ot(k),x=k.bitrate/1e3,ie={width:k.width,height:k.height},V=this.frameRatesByFrameHeight[k.height];if(I){const j={id:E,quality:I,bitrate:x,size:ie,fps:V};this.videoTracks.push({track:j,bitrateInfo:k}),k.qualityIndex===L&&(se=j)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:k})=>k)),se&&e.currentVideoTrack$.next(se),this.videoState.setState(Y.STREAM_INITIALIZED),this.videoState.startTransitionTo(Y.READY)}),i(fe(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const T=m.requestEndDate.getTime()-m.firstByteDate.getTime(),P=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(P,T)}),i(O(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=It(this.videoTracks.map(({track:L})=>L),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),P=this.videoTracks.find(({track:L})=>L===T);P?.bitrateInfo&&this.player.setQualityFor("video",P?.bitrateInfo.qualityIndex,!1)}),i(qe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(U($))}).pipe(U(({isLive:m})=>m),v(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=fe(this.player,"playbackTimeUpdated").pipe(v(({time:m})=>m??0));i(qe({availableFrom:this.availableFrom$.pipe(U($)),currentTime:n}),({availableFrom:m,currentTime:T})=>this.params.output.liveTime$.next(m+T*1e3)),i(n.pipe(U(()=>this.isLive$.getValue()===!1)),e.position$),i(fe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),i(fe(this.player,"playbackEnded"),e.endedEvent$),i(fe(this.player,"playbackProgress").pipe(v(()=>Bs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Y.PLAYING),w(t.playbackState,f.PLAYING)}),i(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),i(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(Y.PAUSED),w(t.playbackState,f.PAUSED)}),i(fe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY)}),i(this.isLive$,e.isLive$),i(qt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));i(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:u,connectionReused$:h}=Ti(this.player);i(u,this.params.output.httpConnectionType$),i(h,this.params.output.httpConnectionReused$),i(c,this.maxSeekBackTime$),i(d.pipe(pe()),e.firstBytesEvent$),i(fe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&i(qe({isLive:this.isLive$,isShort:e.duration$.pipe(v(m=>m<60))}),({isLive:m,isShort:T})=>{const P=!m&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:P}}})}),i(n.pipe(U(m=>m>this.params.tuning.insufficientBufferRuleMargin),pe()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(fe(this.player,"manifestLoaded").pipe(pe()).subscribe(()=>{this.subscription.add(fe(this.player,"playbackPlaying").pipe(pe(),nt(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(dt(this.video,t.isLooped,s));const{volumeState$:l,looped$:p,playbackRateState$:S}=ze(this.video);this.subscription.add(Ge(this.video,t.volume,l,s)),this.subscription.add(l.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,S,s))}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.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Y.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Y.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const i=ft(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ht.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(Y.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===Y.DOWNLOADING_LIB||e===Y.STREAM_INITIALIZED))switch(s?.to!==f.PAUSED&&i.state===B.Requested&&e!==Y.STOPPED&&t!==f.STOPPED&&(a?this.seek(i.position-this.liveOffset.getTotalPausedTime()):this.seek(i.position)),t){case f.STOPPED:{switch(e){case Y.STOPPED:break;case Y.PLAYING:case Y.PAUSED:case Y.READY:this.stop();break;default:N(e)}break}case f.PLAYING:{switch(e){case Y.PLAYING:break;case Y.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Y.READY:this.play();break;case Y.STOPPED:this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case Y.PLAYING:this.pause(),this.liveOffset.pause();break;case Y.PAUSED:break;case Y.READY:this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED);break;case Y.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Ct=r=>{switch(r){case"mobile":return te.Q_144P;case"lowest":return te.Q_240P;case"low":return te.Q_360P;case"sd":case"medium":return te.Q_480P;case"hd":case"high":return te.Q_720P;case"fullhd":case"full":return te.Q_1080P;case"quadhd":case"quad":return te.Q_1440P;case"ultrahd":case"ultra":return te.Q_2160P}},tt=async r=>{const e=r.muted;try{await r.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(s){return r.muted=!1,console.warn(s),!1}}return!0};function ye(){return ce()}function Os(r){return ye()-r}function ds(r){const e=r.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,i=n=>s.test(n);return{resolve:(n,o,c=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return c&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ni(r,e,t){const s=(...i)=>{t.apply(null,i),r.removeEventListener(e,s)};r.addEventListener(e,s)}function Ft(r,e,t,s){const i=window.XMLHttpRequest;let a,n,o,c=!1,d=0,u,h,l=!1,p="arraybuffer",S=7e3,m=2e3,T=()=>{if(c)return;A(u);const W=Os(u);let le;if(W<m){le=m-W,setTimeout(T,le);return}m*=2,m>S&&(m=S),n&&n.abort(),n=new i,I()};const P=W=>(a=W,ne),L=W=>(h=W,ne),se=()=>(p="json",ne),k=()=>{if(!c){if(--d>=0){T(),s&&s();return}c=!0,h&&h(),t&&t()}},E=W=>(l=W,ne),I=()=>{u=ye(),n=new i,n.open("get",r);let W=0,le,Le=0;const We=()=>(A(u),Math.max(u,Math.max(le||0,Le||0)));if(a&&n.addEventListener("progress",C=>{const X=ye();a.updateChunk&&C.loaded>W&&(a.updateChunk(We(),C.loaded-W),W=C.loaded,le=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(c)return;A(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const X=n.response.byteLength-W;X&&a.updateChunk&&a.updateChunk(We(),X)}h&&h(),n&&e(n.response)}else k()}),n.addEventListener("error",()=>{k()}),l){const C=()=>{A(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ye(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=p,n.send(),ne},ne={withBitrateReporting:P,withParallel:E,withJSONResponse:se,withRetryCount:W=>(d=W,ne),withRetryInterval:(W,le)=>($(W)&&(m=W),$(le)&&(S=le),ne),withTimeout:W=>(o=W,ne),withFinally:L,send:I,abort:()=>{n&&(n.abort(),n=void 0),c=!0,h&&h()}};return ne}const Bi=100,Oi=2e3,Mi=500;let Ui=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,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Mi;if(t-e>Oi){let s=0,i=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,i+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const c=a.bytes*n/o;i+=c,a.start=t,a.bytes-=c}}}if(i>0&&s>0){const a=i*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>Bi&&(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 Fi{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=ye(),i=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=c=>{e._complete=1,e._responseData=c,e._downloadTime=ye()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ft(t,a,()=>i("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=ye()}_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=ye();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,i){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=i,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=i,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Bt=1e4,Ot=3,Vi=300,Hi=2e3,qi=6e4,Gi=10,Yi=1,zi=500;class Wi{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 Ui(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ds(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):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=ds(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let i;s!==0&&(i=t.buffered.start(s-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){const{videoElement:t}=this.params;let s,i,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!i||a.bitrate>i.bitrate)&&(i=a):(!s||s.bitrate>a.bitrate)&&(s=a));return i||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||$(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:i,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{Ni(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Fi(Ot,Bt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:i}=this.params;let a=!1,n=null,o=null,c=null,d=null,u=!1;const h=()=>{const k=a&&(!u||u===this.rep);return k||t("Not running!"),k},l=(k,E,I)=>{c&&c.abort(),c=Ft(this.urlResolver.resolve(k,!1),E,I,()=>this._retryCallback()).withTimeout(Bt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ot).withFinally(()=>{c=null}).send()},p=(k,E,I)=>{A(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),E,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=k=>{const E=s.playbackRate;s.playbackRate!==k&&(t(`Playback rate switch: ${E}=>${k}`),s.playbackRate=k)},m=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),T()},T=()=>{if(!this.lowLatency)S(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const I=ye()-6e4;let x=0;for(let V=0;V<this.bufferStates.length;V++){const j=this.bufferStates[V];k=Math.min(k,j.buf),j.ts<I&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${k} drop=${x} jitter=${this.sourceJitter}`);let ie=k-Yi;this.sourceJitter>=0?ie-=this.sourceJitter/2:this.sourceJitter-=1,ie>3?S(1.15):ie>1?S(1.1):ie>.3?S(1.01):S(1)}},P=k=>{let E;const I=()=>E&&E.start?E.start.length:0,x=C=>E.start[C]/1e3,ie=C=>E.dur[C]/1e3,V=C=>E.fragIndex+C,j=(C,X)=>({chunkIdx:V(C),startTS:x(C),dur:ie(C),discontinuity:X}),ne=()=>{let C=0;if(E&&E.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=X;this.sourceJitter>1&&(me+=this.sourceJitter-1);let Ee=E.dur.length-1;for(;Ee>=0&&(me-=E.dur[Ee],!(me<=0));--Ee);C=Math.min(Ee,E.dur.length-1-ue),C=Math.max(C,0)}return j(C,!0)},W=C=>{const X=I();if(!(X<=0)){if($(C)){for(let ue=0;ue<X;ue++)if(x(ue)>C)return j(ue)}return ne()}},le=C=>{const X=I(),ue=C?C.chunkIdx+1:0,me=ue-E.fragIndex;if(!(X<=0)){if(!C||me<0||me-X>Gi)return t(`Resync: offset=${me} bChunks=${X} chunk=`+JSON.stringify(C)),ne();if(!(me>=X))return j(ue-E.fragIndex,!1)}},Le=(C,X,ue)=>{d&&d.abort(),d=Ft(this.urlResolver.resolve(C,!0,this.lowLatency),X,ue,()=>this._retryCallback()).withTimeout(Bt).withRetryCount(Ot).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(C,X)=>{Le(k,ue=>{if(!h())return;E=ue;const me=Boolean(E.lowLatency);me!==this.lowLatency&&m(me);let Ee=0;for(let Qe=0;Qe<E.dur.length;++Qe)Ee+=E.dur[Qe];Ee>0&&(A(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,C(W(X))},()=>this._handleNetworkError())},nextChunk:le}},L=()=>{a=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),A(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:k=>{const{videoElement:E,logger:I}=this.params;let x=P(e.jidxUrl),ie,V,j,ne,W=0,le,Le,We;const C=()=>{le&&(clearTimeout(le),le=void 0);const H=Math.max(zi,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=W+H,Se=ye(),be=Math.min(1e4,ge-Se);W=Se;const Me=()=>{d||h()&&x.seek(()=>{h()&&(W=ye(),X(),C())})};be>0?le=window.setTimeout(()=>{this.paused?C():Me()},be):Me()},X=()=>{let H;for(;H=x.nextChunk(ne);)ne=H,gt(H);const ge=x.nextChunk(j);if(ge){if(j&&ge.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?C():(L(),this._initPlayerWith(e));return}Qe(ge)}else C()},ue=(H,ge)=>{if(!h()||!this.sourceBuffer)return;let Se,be,Me;const Ue=De=>{window.setTimeout(()=>{h()&&ue(H,ge)},De)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const De=ye(),je=E.currentTime;!this.paused&&E.buffered.length>1&&Le===je&&De-We>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),Le!==je&&(Le=je,We=De);const Je=this._getBufferSizeSec();if(Je>30)I(`Buffered ${Je} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:De,buf:Je}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Ke){if(Ke.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(Se=this.sourceBuffer.buffered.start(0),be=je,be-Se>4&&this.sourceBuffer.remove(Se,be-3)),Ue(1e3);else throw Ke}}},me=()=>{V&&ie&&(I([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(j)]),ue(V,function(){V=null,X()}))},Ee=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),Qe=H=>{h()&&p(Ee(H),(ge,Se)=>{if(h()){if(Se/=1e3,V=ge,j=H,n=H.startTS,Se){const be=Math.min(10,H.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}me()}},()=>this._handleNetworkError())},gt=H=>{h()&&(A(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(H),!1)))},xt=H=>{h()&&(e.cachedHeader=H,ue(H,()=>{ie=!0,me()}))};a=!0,x.seek(H=>{if(h()){if(W=ye(),!H){C();return}ne=H,!z(k)||H.startTS>k?Qe(H):(j=H,X())}},k),e.cachedHeader?xt(e.cachedHeader):l(e.headerUrl,xt,()=>this._handleNetworkError())},stop:L,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),$(i)&&(i+=.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,A(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return $(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let l,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),S=h/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}l=this._selectQuality(h),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${h}`)},a=(()=>({updateChunk:(l,p)=>{const S=ye();if(this.chunkRateEstimator.addInterval(l,S,p)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-l,speed:T}),!0}},get:()=>{const l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let h=a.get();if(h&&o&&this.autoQuality){if(c&&h>o&&Os(n)<3e4)return;s(h)}c=this.autoQuality};return{updateChunk:(h,l)=>{const p=a.updateChunk(h,l);return p&&d(),p},notifySwitch:h=>{const l=ye();h<o&&(n=l),o=h}}}_fetchManifest(e,t,s){this.manifestRequest=Ft(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bt).withRetryCount(Ot).withRetryInterval(Vi,Hi).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params,a=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&i.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=d,o.push(c))}),o.sort(function(c,d){return c.video&&d.video?d.video.height-c.video.height:d.bitrate-c.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},qi))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var F;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(F||(F={}));const Qi=[F.PAUSED,F.PLAYING,F.READY],ji=[F.PAUSED,F.PLAYING,F.READY];class Ji{subscription=new K;video;videoState=new ae(F.STOPPED);dash;representations$=new g([]);textTracksManager=new Oe;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new es;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=i=>{e.output.error$.next({id:"DashLiveProvider",category:_.WTF,message:"DashLiveProvider internal logic error",thrown:i})};O(this.videoState.stateChangeStarted$.pipe(v(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(i)}`})}),this.video=Ye(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=ze(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(F.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),v(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(qe({zeroTime:this.zeroTime$.pipe(U($)),position:s.timeUpdate$}).subscribe(({zeroTime:i,position:a})=>this.params.output.liveTime$.next(i+a*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(Ge(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:i}})=>{const a=i&&ui(i);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.to){case F.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(f.STOPPED);break;case F.MANIFEST_READY:case F.READY:break;case F.PAUSED:this.params.desiredState.playbackState.setState(f.PAUSED);break;case F.PLAYING:this.params.desiredState.playbackState.setState(f.PLAYING);break;default:return N(i.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Wi({videoElement:this.video,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},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(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),i=!s&&$(t)?t:It(e.map(({track:n})=>n),{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()})?.id,a=e.find(({track:n})=>n.id===i)?.representation;A(a,"Representations missing"),this.dash.startPlay(a,s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(s)}setVideoTrack(e){const t=this.representations$.getValue().find(({track:s})=>s.id===e)?.representation;A(t,`No such representation ${e}`),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=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.dash.reinit(ft(this.params.source.url,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:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,s=[];for(const i of t){const a=i.name??i.index.toString(10),n=Ct(i.name)??ot(i.video),o=i.bitrate/1e3,c={...i.video};if(!n)continue;const d={id:a,quality:n,bitrate:o,size:c};s.push({track:d,representation:i})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:i})=>i)),this.videoState.getTransition()?.to===F.MANIFEST_READY&&this.videoState.setState(F.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,s=this.representations$.getValue().find(({representation:i})=>i===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),$(s)&&this.params.output.currentVideoTrack$.next(s);break}case"bandwidth":{const{size:t,duration:s}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,s);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s===f.STOPPED){e!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(F.STOPPED));return}if(!t){if(ji.includes(e)){const n=this.params.desiredState.videoTrack.getTransition()?.to;$(n)&&this.setVideoTrack(n);const o=this.params.desiredState.autoVideoTrackSwitching.getTransition();o&&this.setAutoQuality(o.to)}if(i?.to!==f.PAUSED&&a.state===B.Requested&&Qi.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_READY),this.dash.attachSource(ft(this.params.source.url));return;case F.MANIFEST_READY:this.videoState.startTransitionTo(F.READY),this.prepare();break;case F.READY:s===f.PAUSED?this.videoState.setState(F.PAUSED):s===f.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(F.PAUSED)}));return;case F.PLAYING:s===f.PAUSED&&(this.videoState.startTransitionTo(F.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case F.PAUSED:s===f.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(F.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return N(e)}}}}var Ms=r=>{const e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),s=e===null?Dt.HTTP1:e??void 0,i=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:s,reused:i}},lt=(r,e)=>{let t=0;for(let s=0;s<r.length;s++){const i=r.start(s)*1e3,a=r.end(s)*1e3;i<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Ki=r=>{const e=document.createElement("a");return e.href=r,e.origin},Xi=r=>{const e=document.createElement("a");return e.href=r,e.host};class Us{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,a,n){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(A(this._xhr),this._xhr?.status>=400){this._errorCb?.(`Http${this._xhr?.status}`,`XHR response code ${this._xhr?.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Object.fromEntries(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(s=>s.split(":").map(i=>i.trim())));this._headersCb?.(new Headers(t))}else this._xhr.readyState===4?this._completeCb?.(this._xhr.response):this._xhr.readyState===3&&this._progressCb?.(this._xhr.response)}catch(t){throw this._errorCb?.("XHR2CallbackError",`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{this._xhr?.abort(),this._retryTimeout=window.setTimeout(()=>{if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,this._errorCb?.("XHR2Failover","XHR failed, retrying failover host");else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace(Xi(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",t,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Gt{_appendPromiseUint8Array;_lastXhr;_lastStreamUpdatingCallback;_maxBufferDuration=Number.POSITIVE_INFINITY;_isFull=!1;_mediaSource;_sourceBuffer;_onDashCallback;_params;constructor(e){this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t?.()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const i=this._sourceBuffer.buffered;let a=0;for(let n=0,o=i.length;n<o;n++)a+=i.end(n)-i.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,a,n,o){this.abort(()=>{let c=0;const d=Date.now();let u=0,h=0,l=0;const p=m=>{i(Gt._str2ua(m.substr(c))),c=m.length};let S=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(S=mt(S)),this._lastXhr=new Us(S,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const T=Date.now()-d;this._params.onBandwidthChange({size:m.length,duration:T,speed:8*m.length/(T/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),a?.()},m=>{if(m.length-c>o&&p(m),h===0){h=Date.now();return}l=m.length-u;const T=Date.now()-h;l>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:l,duration:T,speed:8*l/(T/1e3)}),l=0,u=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},n,(m,T,P)=>this._params.onError(m,T,P))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Gt._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){this._lastXhr?.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Zi{_params;_representations=[];_appendVector={};_currentRepresentation;_stream;_lastLoadOffset;_loopTimeout;_cachingPaused=!1;_duration=0;STREAM_END_THRESHOLD=1;_video;_buffer;_onDashCallback;_config;constructor(e){this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=e.onDashCallback??(()=>{}),this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},i=t.exec(e),a=i?.[1]==="-"?-1:1,n={years:s(i?.[2],a),months:s(i?.[3],a),weeks:s(i?.[4],a),days:s(i?.[5],a),hours:s(i?.[6],a),minutes:s(i?.[7],a),seconds:s(i?.[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=mt(s)),new Us(s,t,i=>{this.attachManifest(i,t,Ki(s))},void 0,i=>{this._params.onResponseHeaders(i)},(i,a,n)=>this._params.onError(i,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,u)=>{const h=d.attributes.getNamedItem(u);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{const u=d.getElementsByTagName("SegmentBase")[0],h=u&&n(u,"indexRange").split("-"),l=u&&u.getElementsByTagName("Initialization")[0],p=l&&n(l,"range").split("-");if(!p||!h){const se=d.parentElement;if(se?.getAttribute("contentType")==="text"){const k=d.getAttribute("id")??void 0,E=(s?s+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,I=se.getAttribute("lang")??void 0;E&&c.push({id:k,url:E,language:I})}return}const S=.1,m=Number(d.attributes.getNamedItem("bandwidth")?.value),T=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let P;const L=d.attributes.getNamedItem("frameRate")?.value??void 0;P=L?ts(L):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:m,baseURL:T,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:P,bufferSize:S*m/8,bufferLength:S,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:u,url:h})=>{const l=document.createElement("track");l.setAttribute("src",h),d&&l.setAttribute("id",d),u&&l.setAttribute("srclang",u),this._video.appendChild(l)}),this._representations.sort((d,u)=>u.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,i=>{let a=e.initTo-e.initFrom+1;if(!i.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(i.buffer,0,a);const n=new DataView(i.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let c=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const u=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let l=0;l<u;l+=1){const p=d+(n.getUint32(a,!1)&2147483647),S=c+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:c/o,toTime:S/o,fromOffset:d,toOffset:p-1}),d=p,c=S}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,i=>{this._params.onResponseHeaders(i),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let i,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const u=this._appendVector[String(d.fromTime)];u!==i&&(i=u,this._params.onRepresentationPlay(u));let h;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},h*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},c=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Gt({mediaSource:s,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",c),s.removeEventListener("webkitsourceopen",c)};s.addEventListener("sourceopen",c,!1),s.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,i=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=i||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(i.toTime<s.to+a){const n=this._findRef(i.toTime);n&&n.toTime<s.to+a?(this._buffer.smartRemove(i.fromTime-a,n.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(i.fromTime-a,i.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,i.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||z(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let i=0;i<t.length;i++){const a=t[i];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!s||a.fromTime<s.fromTime)&&(s=a)}if(!s){const i=t[t.length-1];if(e>i.toTime)return i}return s}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const s=t[t.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),i=this._video.buffered.end(t);if(e>s&&e<i)return Math.round(i*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var q;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(q||(q={}));const er=[q.PAUSED,q.PLAYING];class tr{videoState=new ae(q.STOPPED);subscription=new K;video;buffer;dash;representations$=new g([]);currentRepresentation$=new g(void 0);params;textTracksManager=new Oe;elementSize$=new g(void 0);dashLiteEvents={idxRequestPing$:new D,responseHeaders$:new D,manifestReady$:new D,representationPlay$:new D,error$:new D};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),O(this.videoState.stateChangeStarted$.pipe(v(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=Ye(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ai(this.video),this.dash=new Zi({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:i,category:_.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:_.WTF,message:"DashProvider internal logic error",thrown:o})},i=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},a=ze(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),this.subscription.add(a.seeking$.subscribe(()=>{z(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===q.PLAYING||this.videoState.getState()===q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(qt(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),w(this.params.desiredState.playbackState,f.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(q.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(v(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:_.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(O(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,M(this.video,"progress")).pipe(v(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),p=i();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let S;if(!p&&$(u))S=u;else{const m=lt(this.video.buffered,this.video.currentTime*1e3),T=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,P=Math.min(m/T,1);S=It(c.map(({track:L})=>L),{container:l,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:P,playbackRate:this.video.playbackRate,current:c.find(({representation:L})=>L===o)?.track})?.id}return $(S)?c.find(({track:m})=>m.id===S)?.representation:void 0}),he()).subscribe(this.currentRepresentation$,s)).add(qe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(U(o=>o.to===q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(U($))}).pipe(pe()).subscribe(()=>this.videoState.setState(q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(U($),he((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?o.height<=c.height:o===c)).subscribe(o=>{const c=lt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!i())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(ve(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=Ms(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(pe(),nt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(U($)).subscribe(this.handleRepresentationPlay,s)).add(O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return N(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),a=(s.name&&Ct(s.name))??ot(s),n=s.bandwidth/1e3,o={width:s.width,height:s.height},c=s.fps;if(!a)continue;const d={id:i,quality:a,bitrate:n,size:o,fps:c};t.push({track:d,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map(({track:s})=>s)),this.videoState.setState(q.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:s})=>s===e)?.track;t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(t.id))};selectRepresentation=()=>{const e=this.currentRepresentation$.getValue();return A(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s===f.STOPPED){e!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(!t)switch(i?.to!==f.PAUSED&&a.state===B.Requested&&er.includes(e)&&this.seek(a.position,a.forcePrecise),e){case q.STOPPED:this.videoState.startTransitionTo(q.MANIFEST_LOADED),this.prepare();return;case q.MANIFEST_LOADED:this.videoState.startTransitionTo(q.INITIAL_REPRESENTATION_SELECTED);return;case q.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(q.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case q.METADATA_LOADED:this.videoState.startTransitionTo(q.READY),this.dash.updateRefsForCurrentTime();return;case q.READY:s===f.PAUSED?(this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):s===f.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:s===f.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):i?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case q.PAUSED:s===f.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}var we;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(we||(we={}));var Yt;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Yt||(Yt={}));var Pe;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Pe||(Pe={}));var Q;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(Q||(Q={}));var St;(function(r){r.MP4="mp4",r.WEBM="webm"})(St||(St={}));var cs=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const sr=(r,e={})=>{const s=e.timeout||1,i=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-i-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},ir=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",us=ir?sr:window.requestIdleCallback;let Fs=!1;try{Fs=Ns()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class rr{bufferFull$=new D;error$=new D;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(s=>{const i={operation:"append",data:e,signal:t,callback:s};this.queue.push(i),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(i=>{const a={operation:"remove",from:e,to:t,signal:s,callback:i};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Fs&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:i}of this.queue)i(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}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:_.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(i){i instanceof DOMException&&i.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):i instanceof DOMException&&i.name==="InvalidStateError"&&t==="remove"||this.error$.next({id:`BufferTaskQueue:${t}`,category:_.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:i}),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:N(t)}}}var hs=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};const Vs=new TextDecoder("ascii"),Hs=r=>{let e=0,t=r.getUint32(e);e+=4;const s=new DataView(r.buffer,r.byteOffset+e,4),i=Vs.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,r.byteLength)-e,n=new DataView(r.buffer,r.byteOffset+e,a);return{id:i,size:t,contents:n}},ar=r=>Vs.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",nr=r=>{const e=Hs(r),t=[];let s=0;const i=()=>{const p=e.contents.getUint32(s);return s+=4,p};if((i()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");i();const o=i(),c=i(),d=i(),u=i()&4294967295;let h=c/o*1e3,l=r.byteOffset+r.byteLength+d;for(let p=0;p<u;p++){const S=i(),m=S>>>31,T=S<<1>>>1,P=i();if(i(),m!==0)throw new Error("Unsupported multilevel sidx");const L=P/o*1e3;t.push({status:Q.NONE,time:{from:h,to:h+L},byte:{from:l,to:l+T-1}}),h+=L,l+=T}return t},or=r=>{let e=0,t=!1,s=!1;for(;e<=r.byteLength&&!t;){const i=new DataView(r.buffer,r.byteOffset+e);try{const a=Hs(i);if(s||=a.id==="mdat",e+a.size<=r.byteLength)e+=a.size;else break}catch{t=!0}}return e>0&&e<=r.byteLength&&s?new DataView(r.buffer,r.byteOffset,e):null},dr={validateData:ar,parseInit:()=>null,getIndexRange:()=>{},parseSegments:nr,parseFeedableSegmentChunk:or};var y;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(y||(y={}));var R;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(R||(R={}));const ls={[y.EBML]:{type:R.Master},[y.EBMLVersion]:{type:R.UnsignedInteger},[y.EBMLReadVersion]:{type:R.UnsignedInteger},[y.EBMLMaxIDLength]:{type:R.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[y.DocType]:{type:R.String},[y.DocTypeVersion]:{type:R.UnsignedInteger},[y.DocTypeReadVersion]:{type:R.UnsignedInteger},[y.Void]:{type:R.Binary},[y.Segment]:{type:R.Master},[y.SeekHead]:{type:R.Master},[y.Seek]:{type:R.Master},[y.SeekID]:{type:R.Binary},[y.SeekPosition]:{type:R.UnsignedInteger},[y.Info]:{type:R.Master},[y.TimestampScale]:{type:R.UnsignedInteger},[y.Duration]:{type:R.Float},[y.Tracks]:{type:R.Master},[y.Chapters]:{type:R.Master},[y.Cluster]:{type:R.Master},[y.Timestamp]:{type:R.UnsignedInteger},[y.SilentTracks]:{type:R.Master},[y.SilentTrackNumber]:{type:R.UnsignedInteger},[y.Position]:{type:R.UnsignedInteger},[y.PrevSize]:{type:R.UnsignedInteger},[y.SimpleBlock]:{type:R.Binary},[y.BlockGroup]:{type:R.Master},[y.EncryptedBlock]:{type:R.Binary},[y.Attachments]:{type:R.Master},[y.Tags]:{type:R.Master},[y.Cues]:{type:R.Master},[y.CuePoint]:{type:R.Master},[y.CueTime]:{type:R.UnsignedInteger},[y.CueTrackPositions]:{type:R.Master},[y.CueTrack]:{type:R.UnsignedInteger},[y.CueClusterPosition]:{type:R.UnsignedInteger},[y.CueRelativePosition]:{type:R.UnsignedInteger},[y.CueDuration]:{type:R.UnsignedInteger},[y.CueBlockNumber]:{type:R.UnsignedInteger},[y.CueCodecState]:{type:R.UnsignedInteger},[y.CueReference]:{type:R.Master},[y.CueRefTime]:{type:R.UnsignedInteger}},qs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=zt(r,t),i=s in ls,a=i?ls[s].type:R.Binary,n=r.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 c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=((n&255>>o)<<(o-1)*8)+zt(c),u=t+o;let h;return u+d>r.byteLength?h=new DataView(r.buffer,r.byteOffset+u):h=new DataView(r.buffer,r.byteOffset+u,d),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:u,tagSize:u+d,value:h,valueSize:d}},zt=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint16(0)<<8|r.getUint8(2);case 4:return r.getUint32(0);case 5:return r.getUint32(0)<<8|r.getUint8(4);case 6:return r.getUint32(0)<<16|r.getUint16(4);case 7:return r.getUint32(0)<<32|r.getUint16(4)<<8|r.getUint8(6);case 8:return r.getUint32(0)<<32|r.getUint32(4)}return 0},He=(r,e)=>{switch(e){case R.SignedInteger:return r.getInt8(0);case R.UnsignedInteger:return zt(r);case R.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(r);case R.UTF8:return new TextDecoder("utf-8").decode(r);case R.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case R.Master:return r;case R.Binary:return r;default:N(e)}},Lt=(r,e)=>{let t=0;for(;t<r.byteLength;){const s=new DataView(r.buffer,r.byteOffset+t),i=qs(s);if(!e(i))return;i.type===R.Master&&Lt(i.value,e),t=i.value.byteOffset-r.byteOffset+i.valueSize}},cr=r=>{if(r.getUint32(0)!==y.EBML)return!1;let e,t,s;const i=qs(r);return Lt(i.value,({tag:a,type:n,value:o})=>(a===y.EBMLReadVersion?e=He(o,n):a===y.DocType?t=He(o,n):a===y.DocTypeReadVersion&&(s=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Gs=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],ur=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],hr=r=>{let e,t,s,i,a=!1,n=!1,o=!1,c,d;return Lt(r,({tag:u,type:h,value:l,valueSize:p})=>{if(u===y.SeekID){const S=He(l,h);d=zt(S)}else u!==y.SeekPosition&&(d=void 0);return u===y.Segment?(e=l.byteOffset,t=l.byteOffset+p):u===y.Info?a=!0:u===y.SeekHead?n=!0:u===y.TimestampScale?s=He(l,h):u===y.Duration?i=He(l,h):u===y.SeekPosition&&d===y.Cues?c=He(l,h):a&&n&&Gs.includes(u)&&(o=!0),!o}),A(e,"Failed to parse webm Segment start"),A(t,"Failed to parse webm Segment end"),A(i,"Failed to parse webm Segment duration"),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(i/1e9*s*1e3),cuesSeekPosition:c}},lr=r=>{if(z(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},fr=(r,e)=>{let t=!1,s=!1;const i=o=>$(o.time)&&$(o.position),a=[];let n;return Lt(r,({tag:o,type:c,value:d})=>{switch(o){case y.Cues:t=!0;break;case y.CuePoint:n&&i(n)&&a.push(n),n={};break;case y.CueTime:n&&(n.time=He(d,c));break;case y.CueTrackPositions:break;case y.CueClusterPosition:n&&(n.position=He(d,c));break;default:t&&Gs.includes(o)&&(s=!0)}return!(t&&s)}),n&&i(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:u}=o,h=a[c+1];return{status:Q.NONE,time:{from:d,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},pr=r=>{let e=0,t=!1;try{Lt(r,s=>s.tag===y.Cluster?s.tagSize<=r.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ur.includes(s.tag)?(e+s.tagSize<=r.byteLength&&(e+=s.tagSize,t||=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(s.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},mr={validateData:cr,parseInit:hr,getIndexRange:lr,parseSegments:fr,parseFeedableSegmentChunk:pr};class fs{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);error$=new D;gaps=[];subscription=new K;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new rt;destroyAbortController=new rt;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;constructor(e,t,s,i,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case St.MP4:this.containerParser=dr;break;case St.WEBM:this.containerParser=mr;break;default:N(s)}this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=_e(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);A(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new rr(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),n=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.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,hs(this.sourceBuffer.buffered));this.bufferLimit=o,this.pruneBuffer(n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);const s=this.initData.get(t.id),i=this.segments.get(t.id);if(A(s,"No init buffer for starting representation"),A(i,"No segments for starting representation"),!(s instanceof ArrayBuffer))return;let a=0;for(const n of i)n.time.from-a>0&&this.gaps.push({representation:t.id,from:a,to:n.time.from}),a=n.time.to;$(t.duration)&&t.duration-a>0&&this.gaps.push({representation:t.id,from:a,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=_e(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);A(t,`No such representation ${e}`);let s=this.initData.get(e);if(z(s)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),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 i=this.getCurrentPosition();$(i)&&this.maintain(i)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new rt,this.abortBuffer()}maintain(e){if(z(this.downloadingRepresentationId)||z(this.playingRepresentationId)||z(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(A(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const i=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=lt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&u>=i.time.to-e+100&&(a=h)}if(isFinite(this.bufferLimit)&&hs(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),i&&i.status!==Q.NONE))return;let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{const u=o.at(0);u&&u.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.allInitsLoaded&&i&&i.status===Q.FED&&!o.length&<(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=s.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(i===c))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);return s?s.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}destroy(){this.initData.clear(),this.segments.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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex(({status:c,time:{from:d,to:u}})=>c===Q.NONE&&(d>s||d<=s&&u>=s)&&u<=s+this.forwardBufferTarget);if(i===-1)return[];if(t!==Pe.BYTE_RANGE)return e.slice(i,i+1);const a=e;let n=0;const o=[];for(let c=i;c<a.length&&n<=this.tuning.dash.segmentRequestSize;c++){const d=a[c];if(n+=d.byte.to+1-d.byte.from,d.status===Q.NONE||d.status===Q.PARTIALLY_EJECTED)o.push(d);else break}return o}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,a,n=e;const{type:o}=t.segmentReference;switch(o){case Pe.BYTE_RANGE:{i=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Pe.TEMPLATE:{const d=e.at(0);i=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:N(o)}for(const d of n)d.status=Q.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await _e(c,async function*(){const d=as(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(i,{range:a,onProgress:(d,u)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,u,c)}catch(h){this.error$.next({id:"SegmentFeeding",category:_.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:c,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&$(s)&&(t=lt(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:_.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,i,a){if(!this.activeSegments.size)return;const n=h=>{this.abortSegment(h.segment)},o=h=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=Q.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const l of this.representations.values())if(l.id!==t)for(const p of this.segments.get(l.id)??[])p.status===Q.FED&&p.time.from===h.segment.time.from&&p.time.to===h.segment.time.to&&(p.status=Q.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,u=e.byteLength;for(const h of this.activeSegments){const{segment:l}=h,p=d===Pe.BYTE_RANGE,S=p?l.byte.to-l.byte.from+1:u;if(h.representationId!==t||!(!p||l.byte.from>=s&&l.byte.to<s+e.byteLength))continue;if(a.aborted){n(h);continue}const T=p?l.byte.from-s:0,P=p?l.byte.to-s:e.byteLength,L=T<i,se=P<=i;if(l.status===Q.DOWNLOADING&&L&&se){l.status=Q.DOWNLOADED,this.activeSegments.delete(h);const k=new DataView(e.buffer,e.byteOffset+T,S);this.sourceBufferTaskQueue.append(k,a).then(E=>E&&!a.aborted?o(h):n(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&L&&(h.loadedBytes=Math.min(S,i-T),h.loadedBytes>h.feedingBytes)){const k=new DataView(e.buffer,e.byteOffset+T+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===S?k:this.containerParser.parseFeedableSegmentChunk(k);E?.byteLength&&(l.status=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then(I=>{if(a.aborted)n(h);else if(I)h.fedBytes+=E.byteLength,h.fedBytes===S&&o(h);else{if(h.feedingBytes<S)return;n(h)}}))}}}abortSegment(e){e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[i,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=us(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?_e(this.destroyAbortController.signal,async function*(){const o=as(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,i)).then(o=>{if(!o)return;const{dataView:c,segments:d}=o,u=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,u),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||z(t)||this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let i=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const u="size"in d?d.size??0:d.byte.to-d.byte.from;i+=u};for(const d of s){if(d.time.to>=t||i>=e)break;d.status===Q.FED&&c(d)}if(o=isFinite(a)&&isFinite(n),!o){i=0,a=1/0,n=-1/0;for(const d of s){if(d.time.from<t+this.forwardBufferTarget||i>e)break;d.status===Q.FED&&c(d)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const u=this.sourceBuffer.buffered.start(d)*1e3,h=this.sourceBuffer.buffered.end(d)*1e3;for(const l of s)if(l.status===Q.NONE&&Math.round(l.time.from)<=Math.round(u)&&Math.round(l.time.to)>=Math.round(h)){a=u,n=h;break}}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let i={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){i=void 0;break}o>s.time.from&&o<s.time.to&&(i.from=o),n<s.time.to&&n>s.time.from&&(i.to=n)}}i&&i.to-i.from>=1&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=us(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(z(this.sourceBuffer)||z(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const i=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:i,to:a})}const t=1;for(const s of this.segments.values())for(const i of s){const{status:a}=i;if(a!==Q.FED&&a!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(i.time.from),o=Math.ceil(i.time.to),c=e.some(u=>u.from-t<=n&&u.to+t>=o),d=e.some(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);c||(d?i.status=Q.PARTIALLY_EJECTED:i.status=Q.NONE)}}}var ut;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(ut||(ut={}));class Sr{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new rt;subscription=new K;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Ms(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=_e(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=mt(t));const s=yield pt(t,{signal:this.abortAllController.signal}).catch($t);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=_e(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?ut.HEADER:ut.PARAM,range:s,onProgress:i,priority:a="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(s)switch(t){case ut.HEADER:{d.append("Range",`${s.from}-${s.to}`);break}case ut.PARAM:{const V=new URL(c,location.href);V.searchParams.append("bytes",`${s.from}-${s.to}`),c=V.toString();break}default:N(t)}this.requestQuic&&(c=mt(c));let u=this.abortAllController.signal;if(n){const V=new rt;if(this.subscription.add(O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{V.abort()}catch(j){$t(j)}})),this.abortAllController.signal.aborted||n.aborted)try{V.abort()}catch(j){$t(j)}u=V.signal}const h=ce(),l=yield pt(c,{priority:a,headers:d,signal:u}).catch($t),p=ce();if(this.throughputEstimator?.addRawRtt(p-h),!l)return null;if(!l.ok||!l.body)return Promise.reject(new Error(`Fetch error ${l.status}: ${l.statusText}`));this.onHeadersReceived(l.headers);const S=parseInt(l.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!S){const V=yield l.arrayBuffer();return this.throughputEstimator?.addRawSpeed(V.byteLength,ce()-p),i?.(new DataView(V),V.byteLength),V}if(!i&&!o)return l.arrayBuffer();const[m,T]=l.body.tee(),P=m.getReader();o&&this.throughputEstimator?.trackStream(T);let L=0;const se=new ArrayBuffer(S),k=new Uint8Array(se),E=new DataView(se);let I=!1;const x=V=>{I=!0,$t(V)},ie=_e(u,async function*({done:V,value:j}){L===0&&this.lastRequestFirstBytes$.next(ce()-h),!u.aborted&&(V?i?.(E,L):j&&(k.set(j,L),L+=j.byteLength,i?.(E,L),yield P?.read().then(ie,x)))}.bind(this));return yield P?.read().then(ie,x),I?null:se}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case Pe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case Pe.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:N(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=_e(this.abortAllController.signal,async function*(e,t,s){if(e.type!==Pe.BYTE_RANGE)return null;const{from:i,to:a}=e.initRange;let n=i,o=a,c=!1,d,u;e.indexRange&&(d=e.indexRange.from,u=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,i),o=Math.max(u,a))),n=Math.min(n,0);const h=yield this.fetch(e.url,{range:{from:n,to:o},priority:s,measureThroughput:!1});if(!h)return null;const l=new DataView(h,i-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l);let S;if(c&&d!==void 0&&u!==void 0)S=new DataView(h,d-n,u-d+1);else{const T=t.getIndexRange(p);if(T){const P=yield this.fetch(e.url,{range:T,priority:s,measureThroughput:!1});if(!P)return null;S=new DataView(P)}}if(!S)throw new ReferenceError("No way to load representation index");const m=t.parseSegments(S,p);return{dataView:new DataView(h),segments:m}}.bind(this));fetchTemplateRepresentation=_e(this.abortAllController.signal,async function*(e,t){if(e.type!==Pe.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});return i?{segments:e.segments.map(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(i)}:null}.bind(this))}const $t=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},ps=r=>{if(!r.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),i=s?.[1]==="-"?-1:1,a={days:e(s?.[5],i),hours:e(s?.[6],i),minutes:e(s?.[7],i),seconds:e(s?.[8],i)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Jt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[i,a]of Object.entries(s)){const n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>z(a)?o:z(c)?a:a.padStart(parseInt(c,10),"0"))}return t},gr=(r,e)=>{const s=new DOMParser().parseFromString(r,"application/xml"),i={video:[],audio:[],text:[]},a=s.children[0],n=a.getElementsByTagName("Period")[0],o=n.children;let c;const d=a.getAttribute("mediaPresentationDuration"),u=n.getAttribute("duration");if(d)c=ps(d);else if(u){const S=ps(u);$(S)&&(c=S)}let h=0;const l=a.getAttribute("profiles")?.split(",")??[],p=l.includes(Yt.WEBM_AS_IN_FFMPEG)||l.includes(Yt.WEBM_AS_IN_SPEC)?St.WEBM:St.MP4;for(const S of o){const m=S.getAttribute("mimeType"),T=S.getAttribute("codecs"),P=S.getAttribute("contentType")??m?.split("/")[0],L=S.getAttribute("profiles")?.split(",")??[],se=S.querySelectorAll("Representation"),k=S.querySelector("SegmentTemplate");if(P!=="text")for(const E of se){const I=E.getAttribute("mimeType")??m,x=E.getAttribute("codecs")??T??"",ie=E.getAttribute("contentType")??I?.split("/")[0]??P,V=S.getAttribute("profiles")?.split(",")??[],j=parseInt(E.getAttribute("width")??"",10),ne=parseInt(E.getAttribute("height")??"",10),W=parseInt(E.getAttribute("bandwidth")??"",10)/1e3,le=E.getAttribute("frameRate")??"",Le=E.getAttribute("quality")??void 0,We=le?ts(le):void 0,C=E.getAttribute("id")??(h++).toString(10),X=ie==="video"?`${ne}p`:ie==="audio"?`${W}Kbps`:x,ue=`${C}@${X}`,me=E.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(me,e).toString(),Qe=[...l,...L,...V];let gt;const xt=E.querySelector("SegmentBase"),H=E.querySelector("SegmentTemplate")??k;if(xt){const Se=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[be,Me]=Se.split("-").map(st=>parseInt(st,10)),Ue={from:be,to:Me},De=E.querySelector("SegmentBase")?.getAttribute("indexRange"),[je,Je]=De?De.split("-").map(st=>parseInt(st,10)):[],Ke=De?{from:je,to:Je}:void 0;gt={type:Pe.BYTE_RANGE,url:Ee,initRange:Ue,indexRange:Ke}}else if(H){const Se={representationId:E.getAttribute("id")??void 0,bandwidth:E.getAttribute("bandwidth")??void 0},be=parseInt(H.getAttribute("timescale")??"",10),Me=H.getAttribute("initialization")??"",Ue=H.getAttribute("media"),De=parseInt(H.getAttribute("startNumber")??"",10)??1,je=Jt(Me,Se);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Je=H.querySelectorAll("SegmentTimeline S")??[],Ke=[];if(Je.length){let st=De,it=0;for(const bt of Je){const ct=parseInt(bt.getAttribute("d")??"",10)*1e3,yt=parseInt(bt.getAttribute("r")??"",10)||0,Tt=parseInt(bt.getAttribute("t")??"",10)??void 0;for(let is=0;is<yt+1;is++){const Qs=Jt(Ue,{...Se,segmentNumber:st.toString(10),segmentTime:Tt.toString(10)}),js=Tt?Tt/be:it;it+=ct/be;const Js=it;st++,Ke.push({time:{from:js,to:Js},url:Qs})}}}else if($(c)){const it=parseInt(H.getAttribute("duration")??"",10)/be*1e3,bt=Math.ceil(c/it);let ct=0;for(let yt=1;yt<bt;yt++){const Tt=Jt(Ue,{...Se,segmentNumber:yt.toString(10),segmentTime:ct.toString(10)});Ke.push({time:{from:ct,to:ct+it},url:Tt}),ct+=it}}gt={type:Pe.TEMPLATE,baseUrl:Ee,initUrl:je,segments:Ke}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!I)continue;const ge={video:we.VIDEO,audio:we.AUDIO,text:we.TEXT}[ie];ge&&i[ge].push({id:ue,kind:ge,segmentReference:gt,profiles:Qe,duration:c,bitrate:W,mime:I,codecs:x,width:j,height:ne,fps:We,quality:Le})}}return{duration:c,container:p,representations:i}},br=["timeupdate","progress","play","seeked","stalled"];var Ae;(function(r){r.NONE="none",r.MANIFEST_LOADED="manifest_loaded",r.REPRESENTATION_SELECTED="representation_selected"})(Ae||(Ae={}));let yr=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new K;fetcher;state$=new ae(Ae.NONE);currentVideoRepresentation$=new g(void 0);error$=new D;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);forceEnded$=new D;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new rt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=_e(this.destroyController.signal,async function*(e,t){this.element=e,this.state$.startTransitionTo(Ae.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(t).catch(n=>this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n}));if(!s)return null;let i;try{i=gr(s??"",t)}catch(n){this.error$.next({id:"ManifestParsing",category:_.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!i)return null;const a=({mime:n,codecs:o})=>Boolean(e.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`));return this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map(([n,o])=>[n,o.filter(a)]))},this.manifest.representations.video.length?this.state$.setState(Ae.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"}),this.manifest}.bind(this));initRepresentations=_e(this.destroyController.signal,async function*(e,t){A(this.manifest),A(this.element),this.state$.startTransitionTo(Ae.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new fs(we.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],$(t)&&(this.audioBufferManager=new fs(we.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const i=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(v(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(v(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.subscription.add(O(this.forceEnded$,qe({allBuffersFull:i,someBufferEnded:a}).pipe(U(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.subscription.add(O(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(n=>this.source?.addEventListener("sourceopen",n))),$(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&$(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Ae.REPRESENTATION_SELECTED),A(this.element),this.subscription.add(O(...br.map(n=>M(this.element,n)),M(window,"online")).subscribe(this.tick,n=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:n})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&cs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}.bind(this));async switchRepresentation(e,t){return{[we.VIDEO]:this.videoBufferManager,[we.AUDIO]:this.audioBufferManager,[we.TEXT]:null}[e]?.switchTo(t)}seek(e,t){A(this.element),A(this.videoBufferManager);let s;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?s=e:s=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),cs(this.element.buffered,s)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(s),this.audioBufferManager?.maintain(s),this.element.currentTime=s/1e3}stop(){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(Ae.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}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=Xs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:_.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const i of s.gaps)s.playingRepresentation$.getValue()===i.representation&&i.from<=e&&i.to>e&&(this.element.duration*1e3-i.to<this.tuning.endGapTolerance?t.push(1/0):t.push(i.to));if(t.length){const s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var oe;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(oe||(oe={}));const Tr=({id:r,width:e,height:t,bitrate:s,fps:i,quality:a})=>{const n=(a?Ct(a):void 0)??ot({width:e,height:t});return n&&{id:r,quality:n,bitrate:s,size:{width:e,height:t},fps:i}},Er=(r,e,t)=>{const s=e.indexOf(t);return r.at(Math.round(r.length*s/e.length))??r.at(-1)};class vr{subscription=new K;videoState=new ae(oe.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new Oe;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Ii;constructor(e){this.params=e,this.video=Ye(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new yr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=ze(this.video),i=c=>{e.error$.next({id:"DashVKProvider",category:_.WTF,message:"DashVKProvider internal logic error",thrown:c})},a=(c,d)=>this.subscription.add(c.subscribe(d,i));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(U($),pe(),nt(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Ge(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,i)),a(qt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),w(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),w(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(U(({to:c})=>c===Ae.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(oe.READY)}));const n=c=>e.error$.next({id:"RepresentationSwitch",category:_.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.stateChangeEnded$,this.elementSize$,M(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c===Ae.NONE||!this.videoTracks.length)return;const u=c===Ae.MANIFEST_LOADED&&!d,h=c===Ae.REPRESENTATION_SELECTED&&!d,l=t.autoVideoTrackSwitching.getState(),p=t.videoTrack.getState(),S=this.videoTracks.find(({track:{id:I}})=>I===p)?.track,m=e.currentVideoTrack$.getValue(),T=lt(this.video.buffered,this.video.currentTime*1e3),P=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,L=Math.min(T/Math.min(P,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),se=Math.max(S&&!l?this.audioRepresentations.get(S.id)?.bitrate??0:0,m?this.audioRepresentations.get(m.id)?.bitrate??0:0),k=It(this.videoTracks.map(({track:I})=>I),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:se,forwardBufferHealth:L,current:m,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),E=l?k??S:S??k;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState(l),this.player.setBufferTarget(P)),u){const I=E&&this.videoTracks.find(({track:x})=>x===E)?.representation;A(I),this.player.initRepresentations(I.id,this.audioRepresentations.get(I.id)?.id)}else if(h){const I=E&&this.videoTracks.find(({track:x})=>x===E)?.representation;if(I){const x=this.audioRepresentations.get(I.id);this.player.switchRepresentation(we.VIDEO,I.id).catch(n),x&&this.player.switchRepresentation(we.AUDIO,x.id).catch(n)}}},i)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(he(),v(c=>c&&this.videoTracks.find(({representation:{id:d}})=>d===c)?.track)).subscribe(e.currentVideoTrack$,i)),this.textTracksManager.connect(this.video,t,e);const o=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((i,a)=>a.bitrate-i.bitrate),s=Array.from(e.representations.video).sort((i,a)=>a.bitrate-i.bitrate);for(const i of s){const a=Tr(i);if(a){this.videoTracks.push({track:a,representation:i});const n=Er(t,s,i);n&&this.audioRepresentations.set(i.id,n)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:i})=>i))}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state===B.Requested&&s?.to!==f.PAUSED&&e!==oe.STOPPED&&t!==f.STOPPED&&this.seek(i.position,i.forcePrecise),t===f.STOPPED){e!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.player.stop(),this.video.setAttribute("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(oe.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(e===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}switch(e){case oe.READY:t===f.PAUSED?(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case oe.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}}const $r=5e3,Fe={};var J;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(J||(J={}));const Mt=(r,e)=>new _t(t=>{const s=(i,a)=>t.next(a);return r.on(e,s),()=>r.off(e,s)});class kr{subscription=new K;videoState=new ae(J.INITIALIZING);video;params;hls;textTracksManager=new Oe;trackLevels=new Map;constructor(e){this.video=Ye(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ve(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),$r);import("hls.js").then(i=>{e||(Fe.Hls=i.default,Fe.Events=i.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){A(Fe.Hls,"hls.js not loaded"),this.hls=new Fe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){A(Fe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:d})},i=ze(this.video),a=(d,u)=>this.subscription.add(d.subscribe(u,s));a(i.timeUpdate$,t.position$),a(i.durationChange$,t.duration$),a(i.ended$,t.endedEvent$),a(i.looped$,t.loopedEvent$),a(i.error$,t.error$),a(i.isBuffering$,t.isBuffering$),a(i.currentBuffer$,t.currentBuffer$),a(i.loadStart$,t.firstBytesEvent$),a(i.playing$,t.firstFrameEvent$),a(i.canplay$,t.canplay$),a(i.seeked$,t.seekedEvent$),this.subscription.add(dt(this.video,e.isLooped,s)),this.subscription.add(Ge(this.video,e.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(Mt(this.hls,Fe.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:_.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),w(e.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),w(e.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},s)),a(Mt(this.hls,Fe.Events.MANIFEST_PARSED).pipe(v(({levels:d})=>d.reduce((u,h)=>{const l=h.name||h.height.toString(10),{width:p,height:S}=h,m=Ct(h.attrs.QUALITY??"")??ot({width:p,height:S});if(!m)return u;const T=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:l.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:p,height:S},fps:T};return this.trackLevels.set(l,{track:P,level:h}),u.push(P),u},[]))),t.availableVideoTracks$),a(Mt(this.hls,Fe.Events.LEVEL_LOADING).pipe(v(({url:d})=>ve(d))),t.hostname$),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:s}));const n=d=>Array.from(this.trackLevels.values()).find(({level:u})=>u===d)?.track,o=Mt(this.hls,Fe.Events.LEVEL_SWITCHED).pipe(v(({level:d})=>n(this.hls.levels[d])));o.pipe(U($)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Be(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(z(d))return;const u=this.trackLevels.get(d)?.level;if(!u)return;const h=this.hls.levels.indexOf(u),l=this.hls.currentLevel,p=this.hls.levels[l];!p||u.bitrate>p.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(v(d=>d?.id)),onError:s})),a(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!==J.INITIALIZING)switch(s?.to!==f.PAUSED&&i.state===B.Requested&&this.seek(i.position),t){case f.STOPPED:switch(e){case J.STOPPED:break;case J.READY:case J.PLAYING:case J.PAUSED:this.stop();break;default:N(e)}break;case f.PLAYING:switch(e){case J.PLAYING:break;case J.STOPPED:this.prepare();break;case J.READY:case J.PAUSED:this.playIfAllowed();break;default:N(e)}break;case f.PAUSED:switch(e){case J.PAUSED:break;case J.STOPPED:this.prepare();break;case J.READY:this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED);break;case J.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(J.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(J.PLAYING),await tt(this.video)||(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))}pause(){this.videoState.startTransitionTo(J.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.setAttribute("src",""),this.video.load(),this.videoState.setState(J.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0)}}const ms="X-Playback-Duration";var Ss=async r=>{const e=await pt(r,{method:"HEAD"});return e.headers.has(ms)?parseInt(e.headers.get(ms),10):void 0};const Ar=r=>{let e=null;if(r.QUALITY&&(e=Ct(r.QUALITY)),!e&&r.RESOLUTION){const[t,s]=r.RESOLUTION.split("x").map(i=>parseInt(i,10));e=ot({width:t,height:s})}return e??null},Ys=async(r,e=r)=>{const i=(await(await pt(r)).text()).split(`
|
|
8
|
+
`),a=[];for(let n=0;n<i.length;n++){const c=i[n].match(/^#EXT-X-STREAM-INF:(.+)/);if(!c)continue;const d=Object.fromEntries(c[1].split(",").map(T=>T.split("="))),u=d.QUALITY??`stream-${d.BANDWIDTH}`,h=Ar(d);let l;d.BANDWIDTH&&(l=parseInt(d.BANDWIDTH,10)/1e3||void 0),!l&&d["AVERAGE-BANDWIDTH"]&&(l=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const p=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let S;if(d.RESOLUTION){const[T,P]=d.RESOLUTION.split("x").map(L=>parseInt(L,10));T&&P&&(S={width:T,height:P})}const m=new URL(i[++n],e).toString();h&&a.push({id:u,quality:h,url:m,bandwidth:l,size:S,fps:p})}return a};var Z;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(Z||(Z={}));class wr{subscription=new K;videoState=new ae(Z.STOPPED);video;params;textTracksManager=new Oe;manifests$=new g([]);maxSeekBackTime$;liveOffset=new es;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=Ye(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:te.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),Ys(ft(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.maxSeekBackTime$=new g(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":a;return s&&!i&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ze(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,s));a(i.ended$,e.endedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.loadedMetadata$,e.firstBytesEvent$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),v(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&$(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const l=this.manifests$.getValue().find(p=>p.id===h);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(ve(l.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),c&&c.from===Z.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===B.Requested&&this.seek(o.position)},s)),this.subscription.add(i.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},s)),this.subscription.add(qe({startTime:this.manifestStartTime$.pipe(U($)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),s)),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:c,quality:d,size:u,bandwidth:h,fps:l})=>({id:c,quality:d,size:u,fps:l,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(z(e))return;const t=ft(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Ss(t).then(s=>{if(!z(s))this.maxSeekBackTime$.next(s);else{const i=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(z(i)||!isFinite(i))try{pt(t).then(a=>a.text()).then(a=>{const n=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(a)?.[1];if(n){const o=new URL(n,t).toString();Ss(o).then(c=>{z(c)||this.maxSeekBackTime$.next(c)})}})}catch{}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===f.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.setAttribute("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(Z.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(i||a){const c=this.videoState.getState();this.videoState.setState(Z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),o.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==f.PAUSED&&o.state===B.Requested){this.videoState.startTransitionTo(Z.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case Z.READY:t===f.PAUSED?(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case Z.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(Z.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)):this.seek(-this.liveOffset.getTotalOffset())):s?.to===f.PAUSED&&(w(this.params.desiredState.playbackState,f.PAUSED),this.liveOffset.pause());return;case Z.CHANGING_MANIFEST:break;default:return N(e)}}}var re;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(re||(re={}));class Pr{subscription=new K;videoState=new ae(re.STOPPED);video;params;textTracksManager=new Oe;manifests$=new g([]);constructor(e){this.params=e,this.video=Ye(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:te.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ve(this.params.source.url)),Ys(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),a=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":a;return s&&!i&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:_.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ze(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.seeked$,e.seekedEvent$),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),w(t.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),w(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s).add(i.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&$(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const l=this.manifests$.getValue().find(p=>p.id===h);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(ve(l.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),c&&c.from===re.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===B.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:c,quality:d,size:u,bandwidth:h,fps:l})=>({id:c,quality:d,size:u,fps:l,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();z(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===f.STOPPED){e!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.setAttribute("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),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(i||a){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:d}=this.video;this.prepare(),o.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:d*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&o.state===B.Requested&&this.seek(o.position),e){case re.READY:t===f.PAUSED?(this.videoState.setState(re.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case re.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return N(e)}}}var de;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(de||(de={}));class Rr{subscription=new K;videoState=new ae(de.STOPPED);video;trackUrls={};params;textTracksManager=new Oe;constructor(e){this.params=e,this.video=Ye(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],i)=>{const a=i.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ze(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,s));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.seeked$,e.seekedEvent$),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),w(t.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),w(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===de.READY&&this.videoState.setState(de.READY);const o=this.params.desiredState.videoTrack.getTransition();o&&$(o.to)&&(this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to].track)),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();A(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];A(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=mt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ve(t))}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===f.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.setAttribute("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(de.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(e===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(a){const{currentTime:o}=this.video;this.prepare(),n.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:o*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&n.state===B.Requested&&this.seek(n.position),e){case de.READY:t===f.PAUSED?(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case de.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}const gs=["stun:videostun.mycdn.me:80"],Dr=1e3,_r=3,Kt=()=>null;class Ir{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Kt;externalStopCallback=Kt;externalErrorCallback=Kt;constructor(e,t){this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:gs}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:_.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),Dr)}normalizeOptions(e={}){const t={stunServerList:gs,maxRetryNumber:_r,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ee;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ee||(ee={}));class Cr{subscription;params;log;video;videoState=new ae(ee.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new K,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ye(e.container),this.liveStreamClient=new Ir(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(this.videoState.stateChangeStarted$.pipe(v(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const i=ze(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(i.timeUpdate$,e.liveTime$),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$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED)},s)).add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING)},s)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ge(this.video,t.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ee.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(f.STOPPED);break;case ee.READY:break;case ee.PAUSED:t.playbackState.setState(f.PAUSED);break;case ee.PLAYING:t.playbackState.setState(f.PLAYING);break;default:return N(n.to)}},s)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:te.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,f.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ee.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===f.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(a){this.prepare();return}switch(e){case ee.READY:t===f.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case ee.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}class bs{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 Boolean(this.current.done)}}var Lr=()=>{const r=window.navigator;return r.userAgentData?r.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const zs=Lr(),Wt=document.createElement("video"),Xe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Wt.canPlayType?.("application/x-mpegurl")||Wt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},xe={mp4:Boolean(Wt.canPlayType?.("video/mp4")),webm:Boolean(Wt.canPlayType?.("video/webm"))},Ze={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},kt=(Ze.h264||Ze.h265)&&Ze.aac,jt=Xe.hls&&xe.mp4,xr=Boolean(window.WebSocket),Nr=()=>Object.keys(Ze).filter(r=>Ze[r]),Br=(r,e=!1)=>r.filter(t=>{switch(t){case b.DASH:return Xe.mse&&xe.mp4&&kt;case b.DASH_SEP:return Xe.mse&&xe.mp4&&kt;case b.DASH_WEBM:return Xe.mse&&xe.webm&&Ze.vp9&&Ze.opus;case b.DASH_LIVE:return Xe.mse&&xe.mp4&&kt;case b.DASH_ONDEMAND:return Xe.mse&&xe.mp4&&kt;case b.HLS:case b.HLS_LIVE:case b.HLS_ONDEMAND:return jt||e&&Xe.mse&&xe.mp4&&kt;case b.MPEG:return xe.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Xe.webrtc&&xr&&Ze.h264&&(xe.mp4||xe.webm);default:return N(t)}}),Or=()=>zs?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:jt?[b.DASH_WEBM,b.DASH_SEP,b.HLS,b.HLS_ONDEMAND,b.DASH_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],Mr=()=>zs?[b.HLS_LIVE,b.WEB_RTC_LIVE,b.DASH_LIVE]:jt?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.DASH_LIVE]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.HLS_LIVE],ys=r=>r?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Ur=r=>new _t(e=>{const t=new K,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(v(({from:d,to:u})=>`${d}-${u}`)),i=r.desiredPlaybackState$.stateChangeEnded$,a=r.providerChanged$,n=new D;let o=0,c="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),r.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),c="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(c),r.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ts={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Fr={cacheDuration:12e4},Vr={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Hr={maxPausedTime:3e4},qr={maxPausedTime:3e4};class Gr{current$=new g({type:void 0});providerError$=new D;noAvailableProvidersError$=new D;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),availableVideoTracks$:new g([]),autoVideoTrackLimitingAvailable$:new g(!1),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new D,willSeekEvent$:new D,seekedEvent$:new D,loopedEvent$:new D,endedEvent$:new D,firstBytesEvent$:new D,firstFrameEvent$:new D,canplay$:new D,isLive$:new g(void 0),liveTime$: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),element$:new g(void 0)};subscription=new K;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Br([...Mr(),...Or()],this.params.tuning.useHlsJs).filter(n=>$(e.sources[n])),{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.filter(n=>!s.includes(n)),...t.filter(n=>s.includes(n))]:t;this.screenFormatsIterator=new bs(i);const a=[...ys(!0),...ys(!1)];this.chromecastFormatsIterator=new bs(a.filter(n=>$(e.sources[n])))}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(z(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:_.WTF,message:"Failed to create provider",thrown:i})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;A(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),i=s.state!==B.None;this.params.desiredState.seekState.setState({state:B.Requested,position:i?s.position:t,forcePrecise:i?s.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case $e.SCREEN:return this.createScreenProvider(t);case $e.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:i}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return A(o),new tr({...n,source:o,config:Fr})}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return A(o),this.params.tuning.useDashJs?new xi({...n,source:o,format:e,config:qr}):new vr({...n,source:o})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return A(o),jt||!this.params.tuning.useHlsJs?new Pr({...n,source:o}):new kr({...n,source:o})}case b.HLS_LIVE:{const o=this.applyFailoverHost(t[e]);return A(o),new wr({...n,source:o,config:Hr})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return A(o),new Rr({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return A(o),new Ji({...n,source:o,config:Vr})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return A(o),new Cr({container:s,source:o,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:i,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return A(o),new mi({connection:o,meta:a,container:s,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?$e.CHROMECAST:$e.SCREEN}chooseFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case $e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return N(e)}}skipFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.next();case $e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return N(e)}}handleNoFormatsError(e){switch(e){case $e.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case $e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return N(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=i=>{const a=new URL(i);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return Object.fromEntries(Object.entries(e).map(([i,a])=>[i,s(a)]))}initProviderErrorHandling(){const e=new K;let t=!1,s=0;return e.add(O(this.providerOutput.error$,Ur({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ts.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(U(({type:i})=>i!==void 0))}).pipe(v(i=>({id:`ProviderHangup:${i}`,category:_.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const i=this.params.desiredState.playbackState.transitionEnded$.pipe(U(({to:a})=>a===f.PLAYING),pe()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{if(this.current$.getValue().destination===$e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=i.category===_.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<Ts.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Es=(r,e,t)=>t*e+(1-t)*r;class vs{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=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 Ne(`raw_${t}`),this.smoothedSeries$=new Ne(`smoothed_${t}`),this.reportedSeries$=new Ne(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let c=0;c<this.pastMeasures.length;c++)this.pastMeasures[c]!==void 0&&(t+=(this.pastMeasures[c]-this.smoothed)**2,s++);t/=s;const i=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=Es(this.slow,e,this.params.emaAlphaSlow),this.fast=Es(this.fast,e,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(z(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 Re;(function(r){r[r.LOCAL_STORAGE=0]="LOCAL_STORAGE",r[r.SESSION_STORAGE=1]="SESSION_STORAGE",r[r.RUNTIME=2]="RUNTIME"})(Re||(Re={}));const Ws=new Map;let at=Re.RUNTIME;const Xt=`vk-videoplayer-dummy-key-${Math.random()}`,Yr=()=>{try{localStorage.setItem(Xt,"test"),localStorage.removeItem(Xt),at=Re.LOCAL_STORAGE}catch(r){if(r instanceof DOMException||r instanceof TypeError)try{sessionStorage.getItem(Xt),at=Re.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)at=Re.RUNTIME;else throw e}else throw r}};Yr();const zr=r=>{switch(at){case Re.LOCAL_STORAGE:return localStorage.getItem(r)??void 0;case Re.SESSION_STORAGE:return sessionStorage.getItem(r)??void 0;case Re.RUNTIME:return Ws.get(r);default:N(at)}},$s=(r,e)=>{switch(at){case Re.LOCAL_STORAGE:try{localStorage.setItem(r,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Re.SESSION_STORAGE:try{sessionStorage.setItem(r,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Re.RUNTIME:return void Ws.set(r,e);default:N(at)}},Wr=5e3,ks="one_video_throughput",As="one_video_rtt",Pt=window.navigator.connection,ws=()=>{const r=Pt?.downlink;if($(r)&&r!==10)return r*1e3},Ps=()=>{const r=Pt?.rtt;if($(r)&&r!==3e3)return r},Rs=(r,e,t)=>{const s=t*8,i=s/r;return s/(i+e)};class Rt{throughput;rtt;subscription=new K;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Rt.load(ks)||(e.useBrowserEstimation?ws():void 0)||Wr,s=Rt.load(As)??(e.useBrowserEstimation?Ps():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(s),this.rttAdjustedThroughput$=new g(Rs(t,s,e.rttPenaltyRequestSize)),this.throughput=new vs({initial:t,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new vs({initial:s,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const i=()=>{const n=ws();n&&this.throughput.next(n);const o=Ps();$(o)&&this.rtt.next(o)};Pt&&"onchange"in Pt&&this.subscription.add(M(Pt,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{$s(ks,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{$s(As,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(qe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(v(({throughput:i,rtt:a})=>Rs(i,a,e.rttPenaltyRequestSize)),U(i=>{const a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(i-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ce();const i=new K;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(M(e,"progress").pipe(pe()).subscribe(a=>{t=a.loaded,s=ce()}));break;case 1:case 0:i.add(M(e,"loadstart").subscribe(()=>{t=0,s=ce()}));break}i.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ce(),c=n-t,d=o-s;this.addRawSpeed(c,d,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let s=0;const i=ce();let a=0,n=ce();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=async({done:d,value:u})=>{d?(this.addRawSpeed(s,ce()-i,1),this.concurrentDownloads.delete(e)):u&&(s+=u.byteLength,a+=u.byteLength,a>=this.tuningConfig.streamMinSampleSize&&ce()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,ce()-n,this.concurrentDownloads.size),a=0,n=ce()),await t?.read().then(c,o))};this.concurrentDownloads.add(e),t?.read().then(c,o)}addRawSpeed(e,t,s=1){if(Rt.sanityCheck(e,t)){const i=e*8/t;this.throughput.next(i*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){const t=zr(e);if($(t))return parseInt(t,10)??void 0}}const Ds={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useDashJs:!1,useHlsJs:!0,webrtc:{connectionRetryMaxNumber:3}},Qr=r=>{const e={};for(const t of Object.keys(Ds)){const s=Ds[t],i=r[t];Array.isArray(s)&&Array.isArray(i)?e[t]=i:typeof s=="object"&&typeof i=="object"?e[t]={...s,...i}:e[t]=i??s}return e};var jr=({seekState:r,position$:e})=>O(r.stateChangeEnded$.pipe(v(({to:t})=>t.state===B.None?void 0:(t.position??NaN)/1e3),U($)),e.pipe(U(()=>r.getState().state===B.None))),Jr=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return A(e,`Wrong container or containerId {${r.container}}`),e};const _s=({playbackState:r,seekState:e,playbackAbort$:t,looped$:s,position$:i})=>new _t(a=>{let n;const o=r.transitionEnded$.pipe(U(p=>(p.from===f.PAUSED||p.from===f.STOPPED)&&p.to===f.PLAYING)),c=r.stateChangeEnded$.pipe(U(p=>p.from===f.PLAYING&&p.to===f.PAUSED)),d=e.stateChangeEnded$.pipe(U(({to:p})=>p.state===B.Requested&&(r.getTransition()?.from??r.getState())===f.PLAYING)),u=e.stateChangeEnded$.pipe(U(({from:p,to:S})=>p.state===B.Applying&&S.state===B.None&&(r.getTransition()?.from??r.getState())===f.PLAYING)),h=O(o,u).pipe(v(()=>i.getValue()),U($)),l=O(O(c,d,t),s).pipe(v(()=>i.getValue()),U($));return new K().add(h.subscribe(p=>{n=p})).add(l.subscribe(p=>{if(z(n)||n===p)return;const S={from:n,to:p};n=void 0,a.next(S)}))});class sa{subscription=new K;domContainer;providerContainer;chromecastInitializer;logger=new Zs;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new ae(f.STOPPED),seekState:new ae({state:B.None}),volume:new ae({volume:1,muted:!1}),videoTrack:new ae(void 0),autoVideoTrackSwitching:new ae(!0),autoVideoTrackLimits:new ae({}),isLooped:new ae(!1),playbackRate:new ae(1),externalTextTracks:new ae([]),currentTextTrack:new ae(void 0),textTrackCuesSettings:new ae({})};info={playbackState$:new g(f.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),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),liveTime$: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),chromecastState$:new g(Te.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0)};events={inited$:new D,started$:new D,willPause$:new D,willResume$:new D,willDestruct$:new D,watchCoverageRecord$:new D,watchCoverageLive$:new D,managedError$:new D,fatalError$:new D,ended$:new D,looped$:new D,seeked$:new D,willSeek$:new D,firstBytes$:new D,firstFrame$:new D,canplay$:new D,log$:new D};experimental={element$:new g(void 0),enableDebugTelemetry$:new g(!1),dumpTelemetry:Ri};constructor(e={}){if(this.initLogs(),this.tuning=Qr(e),this.chromecastInitializer=new ri({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Rt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,i)=>{const a=Reflect.get(t,s,i);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const c=n.map(h=>JSON.stringify(h,(l,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),d=`Player.${String(s)}`,u=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_.WTF,message:u,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Jr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Gr({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},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const e=this.desiredState.playbackState;return e.getState()!==f.PLAYING&&e.startTransitionTo(f.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==f.PAUSED&&e.startTransitionTo(f.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==f.STOPPED&&e.startTransitionTo(f.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.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){return this.chromecastInitializer.castState$.getValue()===Te.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===Te.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){A(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(i=>i.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){A(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(e===void 0||this.providerContainer?.providerOutput.availableTextTracks$.getValue().find(t=>t.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){A(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(z(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===B.None?void 0:t.position;return $(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(O(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(v(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(()=>!this.isPlaybackStarted),U(e=>e.to===f.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case f.PAUSED:this.events.willPause$.next();break;case f.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=ce(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const c=this.desiredState.seekState.getState();c.state===B.Requested?this.desiredState.seekState.setState({...c,state:B.Applying}):this.events.managedError$.next({id:`WillSeekIn${c.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(v(c=>c.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(v(c=>c.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(v(c=>c.map(({quality:d})=>d).sort((d,u)=>Vt(d)?1:Vt(u)?-1:Ut(u,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(c=>{const d={};for(const u of c)u.fps&&(d[u.quality]=u.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.currentVideoTrack$.subscribe(c=>{this.info.currentQuality$.next(c?.quality),this.info.videoBitrate$.next(c?.bitrate);const d=e.providerOutput.element$.getValue();d&&this.info.intrinsicVideoSize$.next({width:d.videoWidth,height:d.videoHeight})})).add(e.providerOutput.hostname$.pipe(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(v(c=>c?{start:c.from,end:c.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(v(c=>c.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(v(c=>c.volume),he()).subscribe(this.info.volume$)).add(jr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(nt(!0)),e.providerOutput.seekedEvent$.pipe(nt(!1))).pipe(he()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(v(c=>({id:"NoProviders",category:_.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(pe(),v(()=>ce()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(pe(),v(()=>ce()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pe(),v(()=>ce()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new g(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:c})=>c===f.PLAYING),pe()).subscribe(()=>s.next(!1)));let i=0;const a=O(e.providerOutput.isBuffering$,t,s).pipe(v(()=>{const c=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return c&&!d}),he());this.subscription.add(a.subscribe(c=>{c?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))}));const n=new K;this.subscription.add(n);const o=O(M(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(U(c=>Boolean(c?.provider))));e.providerOutput.isLive$.pipe(he()).subscribe(c=>{switch(A(this.providerContainer),n.unsubscribe(),c){case!0:{const d=new g(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(u=>d.next(u&&Math.floor(u/1e3)))),n.add(_s({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe(v(({from:u,to:h})=>({start:u,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(_s({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(v(({from:d,to:u})=>({start:d,end:u}))).subscribe(this.events.watchCoverageRecord$));break}})}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(v(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new K;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((s,i)=>s.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(s=>s.length>0),pe()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=It(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})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(O(this.desiredState.videoTrack.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(v(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;A(this.providerContainer),A(e),Pi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>wi(t)),this.providerContainer.current$.subscribe(({type:t})=>Nt("provider",t)),e.duration$.subscribe(t=>Nt("duration",t)),e.availableVideoTracks$.pipe(U(t=>!!t.length),pe()).subscribe(t=>Nt("tracks",t)),this.events.fatalError$.subscribe(new Ne("fatalError")),this.events.managedError$.subscribe(new Ne("managedError")),e.position$.subscribe(new Ne("position")),e.currentVideoTrack$.pipe(v(t=>t?.quality)).subscribe(new Ne("quality")),this.info.currentBuffer$.subscribe(new Ne("buffer")),e.isBuffering$.subscribe(new Ne("isBuffering"))].forEach(t=>this.subscription.add(t)),Nt("codecs",Nr())}}const ia=`${si}@${ti}`;export{Te as ChromecastState,Dt as HttpConnectionType,na as Observable,f as PlaybackState,sa as Player,ia as SDK_VERSION,oa as Subject,da as Subscription,ca as ValueSubject,b as VideoFormat,te as VideoQuality};
|