@vkontakte/videoplayer-core 2.0.65 → 2.0.67
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 +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/package.json +29 -4
- package/packages/{sdk → core}/src/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashIFProvider/dashjsTypes.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashLiveProvider/types.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/FilesFetcher.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashProvider/types.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashProvider/utils/DashLite.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashProvider/utils/stream.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashProvider/utils/xhr2.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/buffer.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/ebml.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/fetcher.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/isobmff.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/mpd.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +1 -1
- package/packages/{sdk → core}/src/providers/DashVKProvider/lib/webm.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/ProviderContainer/types.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/types.d.ts +0 -0
- package/packages/{sdk → core}/src/providers/utils/LiveOffset/types.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/StateMachine/types.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/StatefulIterator/StatefulIterator.spec.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/buffer/getTotalBufferDuration.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/buffer/isPositionBuffered.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/buffer/types.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/link.d.ts +0 -0
- package/packages/{sdk → core}/src/utils/quality/quality.spec.d.ts +0 -0
- package/player/Player.d.ts +1 -1
- package/player/utils/optimisticPosition.d.ts +1 -1
- package/providers/utils/forcePlay.d.ts +1 -1
- package/providers/utils/syncDesiredState.d.ts +2 -2
- package/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -135
- package/providers/DashProvider/utils/DashLite.d.ts +0 -60
- package/utils/buffer/isPositionBuffered.d.ts +0 -3
package/es2018.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.67
|
|
3
|
+
* Tue, 30 Aug 2022 15:03:08 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-67/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as r,fromEvent as a,assertNever as n,merge as o,tap as d,map as u,observableFrom as h,filterChanged as l,assertNonNullable as c,debounce as p,timeout as m,filter as f,mapTo as v,now as g,Observable as S,once as b,combine as y,abortable as T,getExponentialDelay as E,interval as w,throttle as $,Logger as k}from'@vkontakte/videoplayer-shared/es2018.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2018.esm.js';import A from'lodash/debounce';var P,D,_,R,I,L,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_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND_VK',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(D||(D={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(_||(_={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(R||(R={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(I||(I={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(L||(L={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(C||(C={}));class x{constructor(r){var a;this.connection$=new t(void 0),this.castState$=new t(R.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(R.NOT_AVAILABLE),this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const n='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${n}`}),r.isDisabled||!n)return;var o;s(null===(a=window.chrome)||void 0===a?void 0:a.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(o='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',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.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(a(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.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(t.sessionState)}}))).add(o(a(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),h([i.getCastState()])).pipe(l(),u(N),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var n;const o=a===R.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();c(s);const a=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(r(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===R.CONNECTED?s(this.connection$.getValue())?R.CONNECTED:R.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const N=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return R.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return R.AVAILABLE;case cast.framework.CastState.CONNECTING:return R.CONNECTING;case cast.framework.CastState.CONNECTED:return R.CONNECTED;default:return n(t)}};var O;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(O||(O={}));var B,M=(t,e=0,i=O.OFFSET_P)=>{switch(i){case O.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case O.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t},U=(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 V={[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}},q=(t,e)=>V[t].height>V[e].height,F=(t,e)=>V[t].height<V[e].height,H=Object.keys(V).sort(((t,e)=>F(t,e)?-1:1)),G=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return H.find((t=>{const e=V[t];return e.width>=s&&e.height>=i}))},Y=t=>t===B.INVARIANT;class z{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$),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 Q;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Q||(Q={}));class j{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new z(Q.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)if((null==s?void 0:s.to)===P.PAUSED||r.state!==C.Requested||t===Q.STOPPED)switch(i){case P.PLAYING:switch(t){case Q.PLAYING:break;case Q.PAUSED:case Q.READY:this.videoState.startTransitionTo(Q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Q.PLAYING:this.videoState.startTransitionTo(Q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Q.PAUSED:break;case Q.READY:this.videoState.startTransitionTo(Q.PAUSED),this.videoState.setState(Q.PAUSED);break;case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();break;default:n(t)}break;default:n(i)}else this.seek(r.position)}else t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.stop())},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 D.MPEG:case D.DASH:case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.HLS:case D.HLS_JS:case D.HLS_ONDEMAND:return!1;case D.HLS_LIVE:case D.DASH_LIVE:case D.DASH_LIVE_WEBM:return!0;default:return n(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(o(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(p(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(a(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(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(a(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(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),U(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:n(i)}})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(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(Q.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(Q.PLAYING),U(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(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Q.PAUSED&&t!==Q.PLAYING||(this.videoState.setState(Q.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Q.PLAYING&&t!==Q.PAUSED||(this.videoState.setState(Q.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Q.READY&&this.videoState.setState(Q.READY)}handleRemoteStop(){this.videoState.getState()!==Q.STOPPED&&this.videoState.setState(Q.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}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){var e;const i=this.params.source;let r,a,o;switch(t){case D.MPEG:{const e=i[t];c(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===B.INVARIANT?1:e===B.INVARIANT?-1:F(t,e)?1:-1))[0];c(s);const n=e[s];c(n),r=n,a='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS:case D.HLS_ONDEMAND:{const e=i[t];c(e),r=e.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM_VK:case D.DASH_WEBM:{const e=i[t];c(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS_LIVE:{const e=i[t];c(e),r=M(e.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case D.DASH_LIVE_WEBM:{const e=i[t];c(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case D.HLS_JS:case D.DASH:case D.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return n(t)}const d=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:r,a);d.contentUrl=r,d.streamType=o,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:h}=this.params.meta;return s(u)&&(d.metadata.title=u),s(h)&&(d.metadata.subtitle=h),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(m(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',message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}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 K{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&&(K.prototype[Symbol.toStringTag]='AbortController',J.prototype[Symbol.toStringTag]='AbortSignal');const Z=X({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),tt=Z?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!X({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty('signal')||r)&&(a=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const r=new i(t,e);return s&&Object.defineProperty(r,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),r},a.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=a&&a.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 r=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,n(t,e)])}return n(t,e)},Request:a}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=Z?tt.fetch:window.fetch;Z?tt.Request:window.Request;const it=Z?K:window.AbortController,st=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class rt{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}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[r,a]=st(s.request);if(r>=i.from&&a<=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){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),r=this.activeRequests.get(i.url);s&&r&&r.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(st),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 a=new URL(t,location.href);a.searchParams.append('bytes',`${s}-${r}`);const n=a.toString(),o=new it,d=o.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return et(n,{signal:d}).then((t=>{var e,i,a;if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const d=n.getReader(),l=parseInt(null!==(a=t.headers.get('Content-Length'))&&void 0!==a?a:'',10)||r-s+1;u.data=new ArrayBuffer(l);const c=new Uint8Array(u.data),p=async({done:t,value:e})=>{t?this.onBigRequestProgress(u):e&&(c.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),await(null==d?void 0:d.read().then(p,rt.suppressStreamErrors).catch(h)))};null==d||d.read().then(p,rt.suppressStreamErrors).catch(h)}),rt.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,d,u,h,l,c,p;if(!this.activeRequests.has(t)||!r)return;const m=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of m){const{request:m}=n,[f,v]=st(m),g=f>=e&&v<=e+s,S=e>=f&&e+s<v,b=r.slice(f-e,Math.min(v-e+1,s));if((g||S)&&(m.requestStartDate=null!==(o=m.requestStartDate)&&void 0!==o?o:new Date,m.firstByteDate=null!==(d=m.firstByteDate)&&void 0!==d?d:new Date,m.bytesLoaded=b.byteLength,m.bytesTotal=i-e),g){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==n))),null===(h=n.success)||void 0===h||h.call(n,b,'',t);const e=a?Array.from(a.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(m,t,null!==(c=null==a?void 0:a.status)&&void 0!==c?c:200,e,[])}else S&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var r,a,n,o;if(null===(a=(r=this.params).onError)||void 0===a||a.call(r,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const d=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of d){const[r,a]=st(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(o=null==t?void 0:t.error)||void 0===o||o.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=st(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.call(t,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{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 nt=(t,e)=>{const i=new rt(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new at(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var ot=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},dt='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},ut=function(t){return t&&t.Math==Math&&t},ht=ut('object'==typeof globalThis&&globalThis)||ut('object'==typeof window&&window)||ut('object'==typeof self&&self)||ut('object'==typeof dt&&dt)||function(){return this}()||Function('return this')(),lt=function(t){try{return!!t()}catch(t){return!0}},ct=!lt((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),pt=ct,mt=Function.prototype,ft=mt.bind,vt=mt.call,gt=pt&&ft.bind(vt,vt),St=pt?function(t){return t&>(t)}:function(t){return t&&function(){return vt.apply(t,arguments)}},bt=St,yt=bt({}.toString),Tt=bt(''.slice),Et=function(t){return Tt(yt(t),8,-1)},wt=St,$t=lt,kt=Et,At=ht.Object,Pt=wt(''.split),Dt=$t((function(){return!At('z').propertyIsEnumerable(0)}))?function(t){return'String'==kt(t)?Pt(t,''):At(t)}:At,_t=ht.TypeError,Rt=function(t){if(null==t)throw _t('Can\'t call method on '+t);return t},It=Dt,Lt=Rt,Ct=function(t){return It(Lt(t))},xt={},Nt=function(t){return'function'==typeof t},Ot=ht,Bt=Object.defineProperty,Mt=function(t,e){try{Bt(Ot,t,{value:e,configurable:!0,writable:!0})}catch(i){Ot[t]=e}return e},Ut=ht['__core-js_shared__']||Mt('__core-js_shared__',{}),Vt=Nt,qt=Ut,Ft=St(Function.toString);Vt(qt.inspectSource)||(qt.inspectSource=function(t){return Ft(t)});var Ht,Gt,Yt=Nt,zt=qt.inspectSource,Qt=ht.WeakMap,jt=Yt(Qt)&&/native code/.test(zt(Qt)),Wt=Nt,Jt=function(t){return'object'==typeof t?null!==t:Wt(t)},Kt=!lt((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Xt={},Zt=Jt,te=ht.document,ee=Zt(te)&&Zt(te.createElement),ie=function(t){return ee?te.createElement(t):{}},se=ie,re=!Kt&&!lt((function(){return 7!=Object.defineProperty(se('div'),'a',{get:function(){return 7}}).a})),ae=Kt&<((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ne=ht,oe=Jt,de=ne.String,ue=ne.TypeError,he=function(t){if(oe(t))return t;throw ue(de(t)+' is not an object')},le=ct,ce=Function.prototype.call,pe=le?ce.bind(ce):function(){return ce.apply(ce,arguments)},me={},fe=me,ve=ht,ge=Nt,Se=function(t){return ge(t)?t:void 0},be=function(t,e){return arguments.length<2?Se(fe[t])||Se(ve[t]):fe[t]&&fe[t][e]||ve[t]&&ve[t][e]},ye=St({}.isPrototypeOf),Te=ht,Ee=be('navigator','userAgent')||'',we=Te.process,$e=Te.Deno,ke=we&&we.versions||$e&&$e.version,Ae=ke&&ke.v8;Ae&&(Gt=(Ht=Ae.split('.'))[0]>0&&Ht[0]<4?1:+(Ht[0]+Ht[1])),!Gt&&Ee&&(!(Ht=Ee.match(/Edge\/(\d+)/))||Ht[1]>=74)&&(Ht=Ee.match(/Chrome\/(\d+)/))&&(Gt=+Ht[1]);var Pe=Gt,De=lt,_e=!!Object.getOwnPropertySymbols&&!De((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Pe&&Pe<41})),Re=_e&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,Ie=be,Le=Nt,Ce=ye,xe=Re,Ne=ht.Object,Oe=xe?function(t){return'symbol'==typeof t}:function(t){var e=Ie('Symbol');return Le(e)&&Ce(e.prototype,Ne(t))},Be=ht.String,Me=function(t){try{return Be(t)}catch(t){return'Object'}},Ue=Nt,Ve=Me,qe=ht.TypeError,Fe=function(t){if(Ue(t))return t;throw qe(Ve(t)+' is not a function')},He=Fe,Ge=function(t,e){var i=t[e];return null==i?void 0:He(i)},Ye=pe,ze=Nt,Qe=Jt,je=ht.TypeError,We={exports:{}},Je=Ut;(We.exports=function(t,e){return Je[t]||(Je[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.21.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.21.1/LICENSE',source:'https://github.com/zloirock/core-js'});var Ke=Rt,Xe=ht.Object,Ze=function(t){return Xe(Ke(t))},ti=Ze,ei=St({}.hasOwnProperty),ii=Object.hasOwn||function(t,e){return ei(ti(t),e)},si=St,ri=0,ai=Math.random(),ni=si(1..toString),oi=function(t){return'Symbol('+(void 0===t?'':t)+')_'+ni(++ri+ai,36)},di=ht,ui=We.exports,hi=ii,li=oi,ci=_e,pi=Re,mi=ui('wks'),fi=di.Symbol,vi=fi&&fi.for,gi=pi?fi:fi&&fi.withoutSetter||li,Si=function(t){if(!hi(mi,t)||!ci&&'string'!=typeof mi[t]){var e='Symbol.'+t;ci&&hi(fi,t)?mi[t]=fi[t]:mi[t]=pi&&vi?vi(e):gi(e)}return mi[t]},bi=pe,yi=Jt,Ti=Oe,Ei=Ge,wi=function(t,e){var i,s;if('string'===e&&ze(i=t.toString)&&!Qe(s=Ye(i,t)))return s;if(ze(i=t.valueOf)&&!Qe(s=Ye(i,t)))return s;if('string'!==e&&ze(i=t.toString)&&!Qe(s=Ye(i,t)))return s;throw je('Can\'t convert object to primitive value')},$i=Si,ki=ht.TypeError,Ai=$i('toPrimitive'),Pi=function(t,e){if(!yi(t)||Ti(t))return t;var i,s=Ei(t,Ai);if(s){if(void 0===e&&(e='default'),i=bi(s,t,e),!yi(i)||Ti(i))return i;throw ki('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),wi(t,e)},Di=Oe,_i=function(t){var e=Pi(t,'string');return Di(e)?e:e+''},Ri=Kt,Ii=re,Li=ae,Ci=he,xi=_i,Ni=ht.TypeError,Oi=Object.defineProperty,Bi=Object.getOwnPropertyDescriptor;Xt.f=Ri?Li?function(t,e,i){if(Ci(t),e=xi(e),Ci(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Bi(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Oi(t,e,i)}:Oi:function(t,e,i){if(Ci(t),e=xi(e),Ci(i),Ii)try{return Oi(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Ni('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Mi,Ui,Vi,qi=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},Fi=Xt,Hi=qi,Gi=Kt?function(t,e,i){return Fi.f(t,e,Hi(1,i))}:function(t,e,i){return t[e]=i,t},Yi=We.exports,zi=oi,Qi=Yi('keys'),ji=function(t){return Qi[t]||(Qi[t]=zi(t))},Wi={},Ji=jt,Ki=ht,Xi=St,Zi=Jt,ts=Gi,es=ii,is=Ut,ss=ji,rs=Wi,as=Ki.TypeError,ns=Ki.WeakMap;if(Ji||is.state){var os=is.state||(is.state=new ns),ds=Xi(os.get),us=Xi(os.has),hs=Xi(os.set);Mi=function(t,e){if(us(os,t))throw new as('Object already initialized');return e.facade=t,hs(os,t,e),e},Ui=function(t){return ds(os,t)||{}},Vi=function(t){return us(os,t)}}else{var ls=ss('state');rs[ls]=!0,Mi=function(t,e){if(es(t,ls))throw new as('Object already initialized');return e.facade=t,ts(t,ls,e),e},Ui=function(t){return es(t,ls)?t[ls]:{}},Vi=function(t){return es(t,ls)}}var cs={set:Mi,get:Ui,has:Vi,enforce:function(t){return Vi(t)?Ui(t):Mi(t,{})},getterFor:function(t){return function(e){var i;if(!Zi(e)||(i=Ui(e)).type!==t)throw as('Incompatible receiver, '+t+' required');return i}}},ps=ct,ms=Function.prototype,fs=ms.apply,vs=ms.call,gs='object'==typeof Reflect&&Reflect.apply||(ps?vs.bind(fs):function(){return vs.apply(fs,arguments)}),Ss={},bs={},ys={}.propertyIsEnumerable,Ts=Object.getOwnPropertyDescriptor,Es=Ts&&!ys.call({1:2},1);bs.f=Es?function(t){var e=Ts(this,t);return!!e&&e.enumerable}:ys;var ws=Kt,$s=pe,ks=bs,As=qi,Ps=Ct,Ds=_i,_s=ii,Rs=re,Is=Object.getOwnPropertyDescriptor;Ss.f=ws?Is:function(t,e){if(t=Ps(t),e=Ds(e),Rs)try{return Is(t,e)}catch(t){}if(_s(t,e))return As(!$s(ks.f,t,e),t[e])};var Ls=lt,Cs=Nt,xs=/#|\.prototype\./,Ns=function(t,e){var i=Bs[Os(t)];return i==Us||i!=Ms&&(Cs(e)?Ls(e):!!e)},Os=Ns.normalize=function(t){return String(t).replace(xs,'.').toLowerCase()},Bs=Ns.data={},Ms=Ns.NATIVE='N',Us=Ns.POLYFILL='P',Vs=Ns,qs=Fe,Fs=ct,Hs=St(St.bind),Gs=function(t,e){return qs(t),void 0===e?t:Fs?Hs(t,e):function(){return t.apply(e,arguments)}},Ys=ht,zs=gs,Qs=St,js=Nt,Ws=Ss.f,Js=Vs,Ks=me,Xs=Gs,Zs=Gi,tr=ii,er=function(t){var e=function(i,s,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,r)}return zs(t,this,arguments)};return e.prototype=t.prototype,e},ir=function(t,e){var i,s,r,a,n,o,d,u,h=t.target,l=t.global,c=t.stat,p=t.proto,m=l?Ys:c?Ys[h]:(Ys[h]||{}).prototype,f=l?Ks:Ks[h]||Zs(Ks,h,{})[h],v=f.prototype;for(r in e)i=!Js(l?r:h+(c?'.':'#')+r,t.forced)&&m&&tr(m,r),n=f[r],i&&(o=t.noTargetGet?(u=Ws(m,r))&&u.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?Xs(a,Ys):t.wrap&&i?er(a):p&&js(a)?Qs(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Zs(d,'sham',!0),Zs(f,r,d),p&&(tr(Ks,s=h+'Prototype')||Zs(Ks,s,{}),Zs(Ks[s],r,a),t.real&&v&&!v[r]&&Zs(v,r,a)))},sr=Kt,rr=ii,ar=Function.prototype,nr=sr&&Object.getOwnPropertyDescriptor,or=rr(ar,'name'),dr={EXISTS:or,PROPER:or&&'something'===function(){}.name,CONFIGURABLE:or&&(!sr||sr&&nr(ar,'name').configurable)},ur={},hr=Math.ceil,lr=Math.floor,cr=function(t){var e=+t;return e!=e||0===e?0:(e>0?lr:hr)(e)},pr=cr,mr=Math.max,fr=Math.min,vr=cr,gr=Math.min,Sr=function(t){return t>0?gr(vr(t),9007199254740991):0},br=function(t){return Sr(t.length)},yr=Ct,Tr=function(t,e){var i=pr(t);return i<0?mr(i+e,0):fr(i,e)},Er=br,wr=function(t){return function(e,i,s){var r,a=yr(e),n=Er(a),o=Tr(s,n);if(t&&i!=i){for(;n>o;)if((r=a[o++])!=r)return!0}else for(;n>o;o++)if((t||o in a)&&a[o]===i)return t||o||0;return!t&&-1}},$r={includes:wr(!0),indexOf:wr(!1)},kr=ii,Ar=Ct,Pr=$r.indexOf,Dr=Wi,_r=St([].push),Rr=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Ir=function(t,e){var i,s=Ar(t),r=0,a=[];for(i in s)!kr(Dr,i)&&kr(s,i)&&_r(a,i);for(;e.length>r;)kr(s,i=e[r++])&&(~Pr(a,i)||_r(a,i));return a},Lr=Rr,Cr=Object.keys||function(t){return Ir(t,Lr)},xr=Kt,Nr=ae,Or=Xt,Br=he,Mr=Ct,Ur=Cr;ur.f=xr&&!Nr?Object.defineProperties:function(t,e){Br(t);for(var i,s=Mr(e),r=Ur(e),a=r.length,n=0;a>n;)Or.f(t,i=r[n++],s[i]);return t};var Vr,qr=be('document','documentElement'),Fr=he,Hr=ur,Gr=Rr,Yr=Wi,zr=qr,Qr=ie,jr=ji('IE_PROTO'),Wr=function(){},Jr=function(t){return'<script>'+t+'<\/script>'},Kr=function(t){t.write(Jr('')),t.close();var e=t.parentWindow.Object;return t=null,e},Xr=function(){try{Vr=new ActiveXObject('htmlfile')}catch(t){}var t,e;Xr='undefined'!=typeof document?document.domain&&Vr?Kr(Vr):((e=Qr('iframe')).style.display='none',zr.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Jr('document.F=Object')),t.close(),t.F):Kr(Vr);for(var i=Gr.length;i--;)delete Xr.prototype[Gr[i]];return Xr()};Yr[jr]=!0;var Zr,ta,ea,ia=Object.create||function(t,e){var i;return null!==t?(Wr.prototype=Fr(t),i=new Wr,Wr.prototype=null,i[jr]=t):i=Xr(),void 0===e?i:Hr.f(i,e)},sa=!lt((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ra=ht,aa=ii,na=Nt,oa=Ze,da=sa,ua=ji('IE_PROTO'),ha=ra.Object,la=ha.prototype,ca=da?ha.getPrototypeOf:function(t){var e=oa(t);if(aa(e,ua))return e[ua];var i=e.constructor;return na(i)&&e instanceof i?i.prototype:e instanceof ha?la:null},pa=Gi,ma=function(t,e,i,s){s&&s.enumerable?t[e]=i:pa(t,e,i)},fa=lt,va=Nt,ga=ia,Sa=ca,ba=ma,ya=Si('iterator'),Ta=!1;[].keys&&('next'in(ea=[].keys())?(ta=Sa(Sa(ea)))!==Object.prototype&&(Zr=ta):Ta=!0);var Ea=null==Zr||fa((function(){var t={};return Zr[ya].call(t)!==t}));va((Zr=Ea?{}:ga(Zr))[ya])||ba(Zr,ya,(function(){return this}));var wa={IteratorPrototype:Zr,BUGGY_SAFARI_ITERATORS:Ta},$a={};$a[Si('toStringTag')]='z';var ka='[object z]'===String($a),Aa=ht,Pa=ka,Da=Nt,_a=Et,Ra=Si('toStringTag'),Ia=Aa.Object,La='Arguments'==_a(function(){return arguments}()),Ca=Pa?_a:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=Ia(t),Ra))?i:La?_a(e):'Object'==(s=_a(e))&&Da(e.callee)?'Arguments':s},xa=Ca,Na=ka?{}.toString:function(){return'[object '+xa(this)+']'},Oa=ka,Ba=Xt.f,Ma=Gi,Ua=ii,Va=Na,qa=Si('toStringTag'),Fa=function(t,e,i,s){if(t){var r=i?t:t.prototype;Ua(r,qa)||Ba(r,qa,{configurable:!0,value:e}),s&&!Oa&&Ma(r,'toString',Va)}},Ha=wa.IteratorPrototype,Ga=ia,Ya=qi,za=Fa,Qa=xt,ja=function(){return this},Wa=ht,Ja=(Wa.String,Wa.TypeError,St);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Ja(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Ka=ir,Xa=pe,Za=function(t,e,i,s){var r=e+' Iterator';return t.prototype=Ga(Ha,{next:Ya(+!s,i)}),za(t,r,!1,!0),Qa[r]=ja,t},tn=ca,en=Fa,sn=ma,rn=xt,an=dr.PROPER,nn=wa.BUGGY_SAFARI_ITERATORS,on=Si('iterator'),dn=function(){return this},un=Ct,hn=xt,ln=cs;Xt.f;var cn=function(t,e,i,s,r,a,n){Za(i,e,s);var o,d,u,h=function(t){if(t===r&&f)return f;if(!nn&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},l=e+' Iterator',c=!1,p=t.prototype,m=p[on]||p['@@iterator']||r&&p[r],f=!nn&&m||h(r),v='Array'==e&&p.entries||m;if(v&&(o=tn(v.call(new t)))!==Object.prototype&&o.next&&(en(o,l,!0,!0),rn[l]=dn),an&&'values'==r&&m&&'values'!==m.name&&(c=!0,f=function(){return Xa(m,this)}),r)if(d={values:h('values'),keys:a?f:h('keys'),entries:h('entries')},n)for(u in d)(nn||c||!(u in p))&&sn(p,u,d[u]);else Ka({target:e,proto:!0,forced:nn||c},d);return n&&p[on]!==f&&sn(p,on,f,{name:r}),rn[e]=f,d},pn=ln.set,mn=ln.getterFor('Array Iterator');cn(Array,'Array',(function(t,e){pn(this,{type:'Array Iterator',target:un(t),index:0,kind:e})}),(function(){var t=mn(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),hn.Arguments=hn.Array;var fn=xt,vn=Si('iterator'),gn=Array.prototype,Sn=Ca,bn=Ge,yn=xt,Tn=Si('iterator'),En=function(t){if(null!=t)return bn(t,Tn)||bn(t,'@@iterator')||yn[Sn(t)]},wn=pe,$n=Fe,kn=he,An=Me,Pn=En,Dn=ht.TypeError,_n=pe,Rn=he,In=Ge,Ln=Gs,Cn=pe,xn=he,Nn=Me,On=function(t){return void 0!==t&&(fn.Array===t||gn[vn]===t)},Bn=br,Mn=ye,Un=function(t,e){var i=arguments.length<2?Pn(t):e;if($n(i))return kn(wn(i,t));throw Dn(An(t)+' is not iterable')},Vn=En,qn=function(t,e,i){var s,r;Rn(t);try{if(!(s=In(t,'return'))){if('throw'===e)throw i;return i}s=_n(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return Rn(s),i},Fn=ht.TypeError,Hn=function(t,e){this.stopped=t,this.result=e},Gn=Hn.prototype,Yn=_i,zn=Xt,Qn=qi,jn=function(t,e,i){var s,r,a,n,o,d,u,h=i&&i.that,l=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=Ln(e,h),f=function(t){return s&&qn(s,'normal',t),new Hn(!0,t)},v=function(t){return l?(xn(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(c)s=t;else{if(!(r=Vn(t)))throw Fn(Nn(t)+' is not iterable');if(On(r)){for(a=0,n=Bn(t);n>a;a++)if((o=v(t[a]))&&Mn(Gn,o))return o;return new Hn(!1)}s=Un(t,r)}for(d=s.next;!(u=Cn(d,s)).done;){try{o=v(u.value)}catch(t){qn(s,'throw',t)}if('object'==typeof o&&o&&Mn(Gn,o))return o}return new Hn(!1)},Wn=function(t,e,i){var s=Yn(e);s in t?zn.f(t,s,Qn(0,i)):t[s]=i};ir({target:'Object',stat:!0},{fromEntries:function(t){var e={};return jn(t,(function(t,i){Wn(e,t,i)}),{AS_ENTRIES:!0}),e}});var Jn=me.Object.fromEntries,Kn={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Xn=ht,Zn=Ca,to=Gi,eo=xt,io=Si('toStringTag');for(var so in Kn){var ro=Xn[so],ao=ro&&ro.prototype;ao&&Zn(ao)!==io&&to(ao,io,so),eo[so]=eo.Array}var no=Jn,oo=i=>{const r=new t(1/0),a=new e,n=new t(void 0),o=new t(void 0);let d=NaN,u=!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=>{var e,i,a,d,u;const h=no(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in h||'x-playback-duration-millis'in h){const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)}const l=null!==(d=h['x-delivery-type'])&&void 0!==d?d:L.HTTP1,c=null!==(u={1:!0,0:!1}[h['x-reused']])&&void 0!==u?u:void 0;n.next(l),o.next(c)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!u&&(u=!0,a.next(Date.now()-d)),i(...t)},d=Date.now(),u=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a,connectionReused$:o,connectionType$:n}},uo=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},ho=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 lo=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),u=e(),h=r(n),l=new i;return n&&l.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(u,d)||(s(d),h&&t.setState(d)),l.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),h&&t.setState(e.to)}),o)),l},co=(t,e,i)=>lo(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),po=(t,e,i,r)=>lo(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),mo=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class fo{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',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(lo(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(lo(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(lo(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){c(this.video);const{textTracks:t}=this.video;this.subscription.add(a(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(a(t,'addtrack'),a(t,'removetrack'),h(['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(o(a(t,'change'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),l()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(a(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(a(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.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){c(this.video);const e=[...this.video.textTracks];return t?e:e.filter(fo.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){c(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&mo(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){c(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){c(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 vo=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class go{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){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}}class So{constructor(t){this._buffer=[],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:r})=>{const a=s>=t&&s<e,n=r>=t&&r<e;a&&n||(a?i(e,r):n?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var bo=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const n=t.start(a),o=t.end(a);if(n<=e&&e<=o){if(s=n,r=o,!i)return{from:s,to:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{from:s,to:r}};const yo=t=>{const i=e=>a(t,e).pipe(v(void 0)),r=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>a(t,e)))).pipe(u((()=>t.readyState<3)),l()),n=o(a(t,'progress'),a(t,'timeupdate')).pipe(u((()=>bo(t.buffered,t.currentTime)))),d=a(t,'volumechange').pipe(p(0),u((()=>({muted:t.muted,volume:t.volume})))),h=a(t,'error').pipe(u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),c=a(t,'timeupdate').pipe(u((()=>t.currentTime))),m=new e;let g;return c.subscribe((e=>{t.loop&&s(g)&&s(e)&&g>=t.duration-.3&&e<=.3&&m.next(g),g=e})),{playing$:i('playing'),pause$:i('pause').pipe(f((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:m,error$:h,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:c,durationChange$:a(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:r,currentBuffer$:n,volumeState$:d}},To=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var Eo=Ze,wo=br,$o=cr;ir({target:'Array',proto:!0},{at:function(t){var e=Eo(this),i=wo(e),s=$o(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var ko=be('Array','at');let Ao=!1,Po={};const Do=t=>{t(Po)},_o=(t,e)=>{var i;Ao&&(Po.meta=null!==(i=Po.meta)&&void 0!==i?i:{},Po.meta[t]=e)};class Ro{constructor(t){this.name=t}next(t){var e,i;if(!Ao)return;Po.series=null!==(e=Po.series)&&void 0!==e?e:{};const s=null!==(i=Po.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Po.series[this.name]=s}}const Io=new Ro('best_bitrate');class Lo{constructor(){this.history={}}recordSelection(t){this.history[t.id]=g()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Co=(t,{container:e,throughput:i,tuning:a,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:u,current:h,history:l})=>{var c,p,m,f;const v=a.usePixelRatio&&null!==(c=window.devicePixelRatio)&&void 0!==c?c:1,S=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*a.containerSizeFactor,height:e.height*v*a.containerSizeFactor},b=S&&G(S),y=a.considerPlaybackRate&&s(u)?u:1,T=t.filter((t=>!Y(t.quality))).sort(((t,e)=>q(t.quality,e.quality)?-1:1)),E=null===(p=ko(T,-1))||void 0===p?void 0:p.quality,w=null===(m=ko(T,0))||void 0===m?void 0:m.quality,$=r(n)||s(n.min)&&s(n.max)&&F(n.max,n.min)||s(n.min)&&w&&q(n.min,w)||s(n.max)&&E&&F(n.max,E),k=y*(A=null!=d?d:.5,P=a.bitrateFactorAtEmptyBuffer,D=a.bitrateFactorAtFullBuffer,(P-D)*Math.pow(2,-10*A)+D);var A,P,D;const _=T.filter((t=>{const e=!b||F(t.quality,b),u=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*k,l=a.lazyQualitySwitch&&s(a.minBufferToSwitchUp)&&h&&!Y(h.quality)&&(null!=d?d:0)<a.minBufferToSwitchUp&&q(t.quality,h.quality),c=$||(r(n.max)||(p=t.quality,m=n.max,V[p].height<=V[m].height))&&(r(n.min)||((t,e)=>V[t].height>=V[e].height)(t.quality,n.min));var p,m;return e&&u&&!l&&c}))[0];_&&_.bitrate&&Io.next(_.bitrate);const R=null!==(f=null!=_?_:T[Math.ceil((T.length-1)/2)])&&void 0!==f?f:t[0],I=R&&l&&l.history[R.id]&&g()-l.history[R.id]<=a.trackCooldown&&(!l.last||R.id!==l.last.id);if((null==R?void 0:R.id)&&l&&!I&&l.recordSelection(R),I&&(null==l?void 0:l.last)){const t=l.last;return null==l||l.recordSwitch(t),t}return null==l||l.recordSwitch(R),R};var xo=t=>new URL(t).hostname;const No=(t,e=300)=>new S((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()})),Oo={};var Bo;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Bo||(Bo={}));const Mo=(t,e)=>new S((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Uo{constructor(e){this.subscription=new i,this.videoState=new z(Bo.DOWNLOADING_LIB),this.textTracksManager=new fo,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new go,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==Bo.DOWNLOADING_LIB&&t!==Bo.STREAM_INITIALIZED)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&t!==Bo.STOPPED&&e!==P.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case Bo.STOPPED:break;case Bo.PLAYING:case Bo.PAUSED:case Bo.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Bo.PLAYING:break;case Bo.PAUSED:r&&(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 Bo.READY:this.play();break;case Bo.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Bo.PLAYING:this.pause(),this.liveOffset.pause();break;case Bo.PAUSED:break;case Bo.READY:this.videoState.setState(Bo.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Bo.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}},this.video=vo(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(xo(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Oo.MediaPlayer=e.MediaPlayer,Oo.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){c(Oo.MediaPlayer,'dashjs not loaded'),c(Oo.Debug,'dashjs not loaded'),this.player=Oo.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?To(t.frameRate+''):void 0),!0)));(this.params.format===D.DASH_WEBM||this.params.format===D.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=nt(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&&ho(this.player),ot(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:uo})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Bo.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(No(this.video),this.elementSize$),a(Mo(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$),a(Mo(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Mo(this.player,'qualityChangeRendered').pipe(f((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));n.pipe(f(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(f((({to:t})=>t===Bo.STREAM_INITIALIZED)),b()).subscribe((()=>{this.subscription.add(lo(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:n.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add(lo(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),a(Mo(this.player,'bufferStateChanged').pipe(f((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),a(Mo(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type'))&&void 0!==s?s:L.HTTP1,d=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(d),t.hostname$.next(xo(i))})),a(Mo(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 r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=G(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===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(Bo.STREAM_INITIALIZED),this.videoState.startTransitionTo(Bo.READY)})),a(Mo(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)})),a(o(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=Co(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));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(f(s))}).pipe(f((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=Mo(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));a(y({availableFrom:this.availableFrom$.pipe(f(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(d.pipe(f((()=>!1===this.isLive$.getValue()))),t.position$),a(Mo(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Mo(this.player,'playbackEnded'),t.endedEvent$),a(Mo(this.player,'playbackProgress').pipe(u((()=>bo(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Mo(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Bo.PLAYING),U(e.playbackState,P.PLAYING)})),a(Mo(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Bo.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Mo(this.player,'playbackPaused'),(()=>{this.videoState.setState(Bo.PAUSED),U(e.playbackState,P.PAUSED)})),a(Mo(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Bo.READY&&this.videoState.setState(Bo.READY)})),a(this.isLive$,t.isLive$),a(No(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)),this.syncPlayback);const{playbackDuration$:l,ping$:c,connectionType$:m,connectionReused$:g}=oo(this.player);a(m,this.params.output.httpConnectionType$),a(g,this.params.output.httpConnectionReused$),a(l,this.maxSeekBackTime$),a(c.pipe(b()),t.firstBytesEvent$),a(Mo(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(y({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}}})})),a(d.pipe(f((t=>t>this.params.tuning.insufficientBufferRuleMargin)),b()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Mo(this.player,'manifestLoaded').pipe(b()).subscribe((()=>{this.subscription.add(Mo(this.player,'playbackPlaying').pipe(b(),v(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(co(this.video,e.isLooped,i));const{volumeState$:S,looped$:T}=yo(this.video);this.subscription.add(po(this.video,e.volume,S,i)),this.subscription.add(S.subscribe(t.volume$,i)),this.subscription.add(T.subscribe(t.loopedEvent$))}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(Bo.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Bo.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=M(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,O.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Bo.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Bo.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var Vo=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}},qo=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 Fo(){return g()}function Ho(t){return Fo()-t}function Go(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function Yo(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,u,h,l=!1,p=0,m=!1,f='arraybuffer',v=7e3,g=2e3,S=()=>{if(l)return;c(u);const t=Ho(u);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!l){if(--p>=0)return S(),void(r&&r());l=!0,h&&h(),i&&i()}},y=()=>{u=Fo(),o=new a,o.open('get',t);let i,s=0,r=0;const p=()=>(c(u),Math.max(u,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=Fo();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(l)return;c(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(p(),t)}h&&h(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),m){const t=()=>{c(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=Fo(),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=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(h=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),l=!0,h&&h()}};return T}class zo{constructor(t){this.intervals=[],this.currentRate=0,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 r=e-t.start,a=t.end-t.start;i+=r;const n=t.bytes*r/a;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(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 Qo{constructor(t,e,i,s,r){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}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=Fo(),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=Yo(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Fo()-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=Fo()}_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=Fo();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 r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._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(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}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 jo{constructor(t){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=t,this.chunkRateEstimator=new zo(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Go(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=Go(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',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.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,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const a=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:'playing'})):a()}))};a()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qo(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,u=null,h=null,l=!1;const p=()=>{const t=n&&(!l||l===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{u&&u.abort(),u=Yo(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},f=(t,e,i)=>{c(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=Fo()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=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,u=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),l=()=>{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,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=i.dur.length-1;for(;a>=0&&(r-=i.dur[a],!(r<=0));--a);t=Math.min(a,i.dur.length-1-s),t=Math.max(t,0)}return u(t,!0)},m=(t,e,i)=>{h&&h.abort(),h=Yo(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{h=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let h=0;for(let t=0;t<i.dur.length;++t)h+=i.dur[t];h>0&&(c(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(h/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 u(i);return l()}})(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)),l();if(!(n>=s))return u(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),u&&u.abort(),h&&h.abort(),c(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,u,l,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Fo(),s=Math.min(1e4,e-i);w=i;const r=()=>{h||p()&&E.seek((()=>{p()&&(w=Fo(),k(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},k=()=>{let e;for(;e=E.nextChunk(l);)l=e,R(e);const i=E.nextChunk(u);if(i){if(u&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));_(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Fo(),u=i.currentTime;!this.paused&&i.buffered.length>1&&g===u&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,T=d);const h=this._getBufferSizeSec();if(h>30)s(`Buffered ${h} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),S(),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&&(r=this.sourceBuffer.buffered.start(0),a=u,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},P=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(u)]),A(d,(function(){d=null,k()})))},D=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),_=t=>{p()&&f(D(t),((e,i)=>{if(p()){if(i/=1e3,d=e,u=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()))},R=t=>{p()&&(c(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{a=!0,P()})))};n=!0,E.seek((t=>{p()&&(w=Fo(),t?(l=t,!r(e)||t.startTS>e?_(t):(u=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},l}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.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,c(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),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,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.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=Fo();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(n&&t>r&&Ho(a)<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=Fo();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Yo(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;qo(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0: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 Wo;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Wo||(Wo={}));const Jo=[Wo.PAUSED,Wo.PLAYING,Wo.READY],Ko=[Wo.PAUSED,Wo.PLAYING,Wo.READY];class Xo{constructor(e){this.subscription=new i,this.videoState=new z(Wo.STOPPED),this.representations$=new t([]),this.textTracksManager=new fo,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new go,this._dashCb=t=>{var e,i,r,a;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}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,a=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),r=null!==(i=Vo(t.name))&&void 0!==i?i:G(t.video),n=t.bitrate/1e3,o={...t.video};if(!r)continue;const d={id:s,quality:r,bitrate:n,size:o};a.push({track:d,representation:t})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===Wo.MANIFEST_READY&&this.videoState.setState(Wo.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(a=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===a?void 0:a.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)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r!==P.STOPPED){if(!i){if(Ko.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}if((null==a?void 0:a.to)!==P.PAUSED&&o.state===C.Requested&&Jo.includes(e))this.seek(o.position-this.liveOffset.getTotalPausedTime());else switch(e){case Wo.STOPPED:return this.videoState.startTransitionTo(Wo.MANIFEST_READY),void this.dash.attachSource(M(this.params.source.url));case Wo.MANIFEST_READY:this.videoState.startTransitionTo(Wo.READY),this.prepare();break;case Wo.READY:return void(r===P.PAUSED?this.videoState.setState(Wo.PAUSED):r===P.PLAYING&&(this.videoState.startTransitionTo(Wo.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Wo.PAUSED)}))));case Wo.PLAYING:return void(r===P.PAUSED&&(this.videoState.startTransitionTo(Wo.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Wo.PAUSED:return void(r===P.PLAYING&&(this.videoState.startTransitionTo(Wo.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(Wo.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(e)}}}else e!==Wo.STOPPED&&(this.videoState.startTransitionTo(Wo.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Wo.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const r=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};o(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=vo(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(xo(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const a=yo(this.video);this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Wo.READY&&this.videoState.setState(Wo.READY)}),r)).add(a.pause$.subscribe((()=>{this.videoState.setState(Wo.PAUSED)}),r)).add(a.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Wo.PLAYING)}),r)).add(a.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(l(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(f(s)),position:a.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),r)).add(co(this.video,this.params.desiredState.isLooped,r)).add(po(this.video,this.params.desiredState.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(this.params.output.volume$,r)).add(a.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(a.playing$.subscribe(this.params.output.firstFrameEvent$)).add(a.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&V[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Wo.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case Wo.MANIFEST_READY:case Wo.READY:break;case Wo.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case Wo.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),r)).add(o(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new jo({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(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),u=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&s(d)?d:null===(a=Co(o.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()}))||void 0===a?void 0:a.id,l=null===(n=o.find((({track:t})=>t.id===h)))||void 0===n?void 0:n.representation;c(l,'Representations missing'),this.dash.startPlay(l,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(h),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;c(i,`No such representation ${t}`),this.dash.switchByName(i.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(M(this.params.source.url,i))}}var Zo=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?L.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}},td=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)};class ed{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,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=()=>{var e,i,s,r,a,n,o,d;if(c(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=no(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'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 id{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,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),null==e||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,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let u=0,h=0,l=0;const c=t=>{s(id._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=uo(p)),this._lastXhr=new ed(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(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}),null==r||r()}),(t=>{if(t.length-o>n&&c(t),0===h)return void(h=Date.now());l=t.length-u;const e=Date.now()-h;l>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:l,duration:e,speed:8*l/(e/1e3)}),l=0,u=t.length,h=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.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(),null==t||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=id._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(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class sd{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},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='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=uo(i)),new ed(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,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,u,h,l,c,p,m,f,v,g,S,b,y,T,E,w,$;const k=t.getElementsByTagName('SegmentBase')[0],A=k&&r(k,'indexRange').split('-'),P=k&&k.getElementsByTagName('Initialization')[0],D=P&&r(P,'range').split('-');if(!D||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(h=null===(u=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===u?void 0:u[0])||void 0===h?void 0:h.data),c=null!==(l=e.getAttribute('lang'))&&void 0!==l?l:void 0;a&&n.push({id:r,url:a,language:c})}return}const _=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const L=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;I=L?To(L):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:_,baseURL:R,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(D[0]),initTo:Number(D[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*_/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,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 r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const u=t.refs[t.refs.length-1];u.toTime-u.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,r;const a=()=>{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 a;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');a=e.to-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.to&&(r=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*a)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}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 id({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 r=this._findRef(e);if(r){if(i){this._isLastRef(r)&&e>=r.toTime&&(e=r.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),a=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:r.fromTime}this._appendVector[String(r.fromTime)]=t,this._stream.load(t,r.fromOffset,r.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=r.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 r=.1;if(s.toTime<i.to+r){const e=this._findRef(s.toTime);e&&e.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((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){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.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 rd;!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'}(rd||(rd={}));const ad=[rd.PAUSED,rd.PLAYING];class nd{constructor(s){this.videoState=new z(rd.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new fo,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&Vo(a.name))&&void 0!==s?s:G(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!n)continue;const h={id:t,quality:n,bitrate:o,size:d,fps:u};r.push({track:h,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(rd.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return c(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)switch((null==s?void 0:s.to)!==P.PAUSED&&r.state===C.Requested&&ad.includes(t)&&this.seek(r.position,r.forcePrecise),t){case rd.STOPPED:return this.videoState.startTransitionTo(rd.MANIFEST_LOADED),void this.prepare();case rd.MANIFEST_LOADED:return void this.videoState.startTransitionTo(rd.INITIAL_REPRESENTATION_SELECTED);case rd.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(rd.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case rd.METADATA_LOADED:return this.videoState.startTransitionTo(rd.READY),void this.dash.updateRefsForCurrentTime();case rd.READY:return void(i===P.PAUSED?(this.videoState.setState(rd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(rd.PLAYING),this.playIfAllowed()));case rd.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(rd.PAUSED),this.video.pause()):(null==s?void 0:s.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case rd.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(rd.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==rd.STOPPED&&(this.videoState.startTransitionTo(rd.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(rd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=s,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(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=vo(s.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(xo(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new So(this.video),this.dash=new sd({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})},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',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=yo(this.video),c=(t,e)=>this.subscription.add(t.subscribe(e,i));c(d.timeUpdate$,t.position$),c(d.durationChange$,t.duration$),c(d.ended$,t.endedEvent$),c(d.looped$,t.loopedEvent$),c(d.error$,t.error$),c(d.isBuffering$,t.isBuffering$),c(d.playing$,t.firstFrameEvent$),c(d.canplay$,t.canplay$),this.subscription.add(d.seeking$.subscribe((()=>{r(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===rd.PLAYING||this.videoState.getState()===rd.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(co(this.video,e.isLooped,i)),this.subscription.add(po(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),c(No(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===rd.READY&&this.videoState.setState(rd.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(rd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(rd.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(rd.METADATA_LOADED)}),i)).add(d.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}`,message:e,thrown:i})))).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$,a(this.video,'progress')).pipe(u((()=>{var t,e,i;const r=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),h=this.elementSize$.getValue(),l=n();let c;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!l&&s(d))c=d;else{const i=td(this.video.buffered,1e3*this.video.currentTime),s=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,n=Math.min(i/s,1);c=null===(e=Co(a.map((({track:t})=>t)),{container:h,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:n,playbackRate:this.video.playbackRate,current:null===(t=a.find((({representation:t})=>t===r)))||void 0===t?void 0:t.track}))||void 0===e?void 0:e.id}return s(c)?null===(i=a.find((({track:t})=>t.id===c)))||void 0===i?void 0:i.representation:void 0})),l()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(f((t=>t.to===rd.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(f(s))}).pipe(b()).subscribe((()=>this.videoState.setState(rd.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(f(s),l(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=td(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(xo(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Zo(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(b(),v(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(f(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(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 n(t)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){qo(this.video).then((t=>{t||(this.videoState.setState(rd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var od,dd,ud,hd,ld;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(od||(od={})),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'}(dd||(dd={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(ud||(ud={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(hd||(hd={})),function(t){t.MP4='mp4',t.WEBM='webm'}(ld||(ld={}));var cd=(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 pd='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;var md,fd,vd=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let gd=!1;try{gd=vd()&&parseInt(null!==(fd=null===(md=navigator.userAgent.match(/Version\/(\d+)/))||void 0===md?void 0:md[1])&&void 0!==fd?fd:'',10)<16}catch(t){console.error(t)}class Sd{constructor(t){this.bufferFull$=new e,this.error$=new e,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown: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 r={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(r),this.pull()}))}async abort(){return new Promise((t=>{const e={operation:'abort',callback:t};for(const{callback:t}of this.queue)t(!1);this.queue=[e],this.pull()}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var t;if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===i&&this.bufferFull$.next(this.currentTask.data.byteLength),t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===i||this.error$.next({id:`BufferTaskQueue:${i}`,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':gd||this.buffer.abort();break;default:n(e)}}}var bd;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(bd||(bd={}));class yd{constructor({throughputEstimator:e,requestQuic:s}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new it,this.subscription=new i,this.fetchManifest=T(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=uo(e));const i=yield et(e,{signal:this.abortAllController.signal}).catch(Td);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetch=T(this.abortAllController.signal,async function*(t,{rangeMethod:e=bd.HEADER,range:i,onProgress:s,priority:r='auto',signal:d,measureThroughput:u=!0}={}){var h,l,c,p;let m=t;const f=new Headers;if(i)switch(e){case bd.HEADER:f.append('Range',`${i.from}-${i.to}`);break;case bd.PARAM:{const t=new URL(m,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),m=t.toString();break}default:n(e)}this.requestQuic&&(m=uo(m));let v=this.abortAllController.signal;if(d){const t=new it;if(this.subscription.add(o(a(this.abortAllController.signal,'abort'),a(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){Td(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){Td(t)}v=t.signal}const S=g(),b=yield et(m,{priority:r,headers:f,signal:v}).catch(Td),y=g();if(null===(h=this.throughputEstimator)||void 0===h||h.addRawRtt(y-S),!b)return null;if(!b.ok||!b.body)return Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const E=parseInt(null!==(l=b.headers.get('Content-Length'))&&void 0!==l?l:'',10)||i&&i.to-i.from+1||NaN;if(!E){const t=yield b.arrayBuffer();return null===(c=this.throughputEstimator)||void 0===c||c.addRawSpeed(t.byteLength,g()-y),null==s||s(new DataView(t),t.byteLength),t}if(!s&&!u)return b.arrayBuffer();const[w,$]=b.body.tee(),k=w.getReader();u&&(null===(p=this.throughputEstimator)||void 0===p||p.trackStream($));let A=0;const P=new ArrayBuffer(E),D=new Uint8Array(P),_=new DataView(P);let R=!1;const I=t=>{R=!0,Td(t)},L=T(v,async function*({done:t,value:e}){0===A&&this.lastRequestFirstBytes$.next(g()-S),v.aborted||(t?null==s||s(_,A):e&&(D.set(e,A),A+=e.byteLength,null==s||s(_,A),yield null==k?void 0:k.read().then(L,I)))}.bind(this));return yield null==k?void 0:k.read().then(L,I),R?null:P}.bind(this)),this.fetchByteRangeRepresentation=T(this.abortAllController.signal,async function*(t,e,i){if(t.type!==ud.BYTE_RANGE)return null;const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,u=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,u=r+1===a,u&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0);const h=yield this.fetch(t.url,{rangeMethod:bd.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!h)return null;const l=new DataView(h,s-o,r-o+1);if(!e.validateData(l))throw new Error('Invalid media file');const c=e.parseInit(l);let p;if(u&&void 0!==a&&void 0!==n)p=new DataView(h,a-o,n-a+1);else{const s=e.getIndexRange(c);if(s){const e=yield this.fetch(t.url,{rangeMethod:bd.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,c);return{dataView:new DataView(h),segments:m}}.bind(this)),this.fetchTemplateRepresentation=T(this.abortAllController.signal,async function*(t,e){if(t.type!==ud.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:hd.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=s}onHeadersReceived(t){const{type:e,reused:i}=Zo(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchRepresentation(t,e,i='auto'){var s,r;const{type:a}=t;switch(a){case ud.BYTE_RANGE:return null!==(s=await this.fetchByteRangeRepresentation(t,e,i))&&void 0!==s?s:null;case ud.TEMPLATE:return null!==(r=await this.fetchTemplateRepresentation(t,i))&&void 0!==r?r:null;default:n(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Td=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Ed=new TextDecoder('ascii'),wd=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=Ed.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}},$d={validateData:t=>'ftyp'===Ed.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=wd(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=4294967295&r();let u=n/a*1e3,h=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:hd.NONE,time:{from:u,to:u+o},byte:{from:h,to:h+s-1}}),u+=o,h+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const r=new DataView(t.buffer,t.byteOffset+e);try{const i=wd(r);if(s||(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 kd,Ad;!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'}(kd||(kd={})),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'}(Ad||(Ad={}));const Pd={[kd.EBML]:{type:Ad.Master},[kd.EBMLVersion]:{type:Ad.UnsignedInteger},[kd.EBMLReadVersion]:{type:Ad.UnsignedInteger},[kd.EBMLMaxIDLength]:{type:Ad.UnsignedInteger},[kd.EBMLMaxSizeLength]:{type:Ad.UnsignedInteger},[kd.DocType]:{type:Ad.String},[kd.DocTypeVersion]:{type:Ad.UnsignedInteger},[kd.DocTypeReadVersion]:{type:Ad.UnsignedInteger},[kd.Void]:{type:Ad.Binary},[kd.Segment]:{type:Ad.Master},[kd.SeekHead]:{type:Ad.Master},[kd.Seek]:{type:Ad.Master},[kd.SeekID]:{type:Ad.Binary},[kd.SeekPosition]:{type:Ad.UnsignedInteger},[kd.Info]:{type:Ad.Master},[kd.TimestampScale]:{type:Ad.UnsignedInteger},[kd.Duration]:{type:Ad.Float},[kd.Tracks]:{type:Ad.Master},[kd.Chapters]:{type:Ad.Master},[kd.Cluster]:{type:Ad.Master},[kd.Timestamp]:{type:Ad.UnsignedInteger},[kd.SilentTracks]:{type:Ad.Master},[kd.SilentTrackNumber]:{type:Ad.UnsignedInteger},[kd.Position]:{type:Ad.UnsignedInteger},[kd.PrevSize]:{type:Ad.UnsignedInteger},[kd.SimpleBlock]:{type:Ad.Binary},[kd.BlockGroup]:{type:Ad.Master},[kd.EncryptedBlock]:{type:Ad.Binary},[kd.Attachments]:{type:Ad.Master},[kd.Tags]:{type:Ad.Master},[kd.Cues]:{type:Ad.Master},[kd.CuePoint]:{type:Ad.Master},[kd.CueTime]:{type:Ad.UnsignedInteger},[kd.CueTrackPositions]:{type:Ad.Master},[kd.CueTrack]:{type:Ad.UnsignedInteger},[kd.CueClusterPosition]:{type:Ad.UnsignedInteger},[kd.CueRelativePosition]:{type:Ad.UnsignedInteger},[kd.CueDuration]:{type:Ad.UnsignedInteger},[kd.CueBlockNumber]:{type:Ad.UnsignedInteger},[kd.CueCodecState]:{type:Ad.UnsignedInteger},[kd.CueReference]:{type:Ad.Master},[kd.CueRefTime]:{type:Ad.UnsignedInteger}},Dd=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=_d(t,i),r=s in Pd,a=r?Pd[s].type:Ad.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),u=((n&255>>o)<<8*(o-1))+_d(d),h=i+o;let l;return l=h+u>t.byteLength?new DataView(t.buffer,t.byteOffset+h):new DataView(t.buffer,t.byteOffset+h,u),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+u,value:l,valueSize:u}},_d=(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},Rd=(t,e)=>{switch(e){case Ad.SignedInteger:return t.getInt8(0);case Ad.UnsignedInteger:return _d(t);case Ad.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Ad.String:return new TextDecoder('ascii').decode(t);case Ad.UTF8:return new TextDecoder('utf-8').decode(t);case Ad.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Ad.Master:case Ad.Binary:return t;default:n(e)}},Id=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Dd(s);if(!e(r))return;r.type===Ad.Master&&Id(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Ld=[kd.Info,kd.SeekHead,kd.Tracks,kd.Chapters,kd.Cluster,kd.Cues,kd.Attachments,kd.Tags],Cd=[kd.Timestamp,kd.SilentTracks,kd.SilentTrackNumber,kd.Position,kd.PrevSize,kd.SimpleBlock,kd.BlockGroup,kd.EncryptedBlock],xd={validateData:t=>{if(t.getUint32(0)!==kd.EBML)return!1;let e,i,s;const r=Dd(t);return Id(r.value,(({tag:t,type:r,value:a})=>(t===kd.EBMLReadVersion?e=Rd(a,r):t===kd.DocType?i=Rd(a,r):t===kd.DocTypeReadVersion&&(s=Rd(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,u=!1;return Id(t,(({tag:t,type:h,value:l,valueSize:c})=>{if(t===kd.SeekID){const t=Rd(l,h);n=_d(t)}else t!==kd.SeekPosition&&(n=void 0);return t===kd.Segment?(e=l.byteOffset,i=l.byteOffset+c):t===kd.Info?o=!0:t===kd.SeekHead?d=!0:t===kd.TimestampScale?s=Rd(l,h):t===kd.Duration?r=Rd(l,h):t===kd.SeekPosition&&n===kd.Cues?a=Rd(l,h):o&&d&&Ld.includes(t)&&(u=!0),!u})),c(e,'Failed to parse webm Segment start'),c(i,'Failed to parse webm Segment end'),c(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},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,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return Id(t,(({tag:t,type:e,value:s})=>{switch(t){case kd.Cues:i=!0;break;case kd.CuePoint:o&&a(o)&&n.push(o),o={};break;case kd.CueTime:o&&(o.time=Rd(s,e));break;case kd.CueTrackPositions:break;case kd.CueClusterPosition:o&&(o.position=Rd(s,e));break;default:i&&Ld.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:hd.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Id(t,(s=>s.tag===kd.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Cd.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[kd.SimpleBlock,kd.BlockGroup,kd.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class Nd{constructor(o,d,u,h,{fetcher:l,tuning:p,getCurrentPosition:m}){switch(this.onLastSegment$=new t(!1),this.fullyBuffered$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.gaps=[],this.subscription=new i,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new it,this.destroyAbortController=new it,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=T(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);c(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new Sd(this.sourceBuffer),this.subscription.add(a(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(a(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>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(c(i,'No init buffer for starting representation'),c(r,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let n=0;for(const t of r)t.time.from-n>=300&&this.gaps.push({representation:e.id,from:n,to:t.time.from}),n=t.time.to;s(e.duration)&&e.duration-n>=300&&this.gaps.push({representation:e.id,from:n,to:e.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=T(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const e=this.representations.get(t);c(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)),this.fetcher=l,this.tuning=p,this.forwardBufferTarget=p.dash.forwardBufferTargetAuto,this.getCurrentPosition=m,this.container=u,u){case ld.MP4:this.containerParser=$d;break;case ld.WEBM:this.containerParser=xd;break;default:n(u)}this.initData=new Map(h.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(h.map((t=>[t.id,t]))),this.kind=o,this.mediaSource=d,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new it,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(c(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=td(this.sourceBuffer.buffered,t),r=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(a=r)}let n=[];if(isFinite(this.bufferLimit)&&(t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e})(this.sourceBuffer.buffered)>=.8*this.bufferLimit)this.pruneBuffer(1/0);else 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=ko(n,0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===hd.FED&&!n.length&&td(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=ko(i,-1);o&&o.status===hd.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){var e,i,s;const r=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!r)return;const a=this.segments.get(r);if(!a)return;const n=a.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.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===hd.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==ud.BYTE_RANGE)return t.slice(s,s+1);const r=t;let a=0;const n=[];for(let t=s;t<r.length&&a<=this.tuning.dash.segmentRequestSize;t++){const e=r[t];if(a+=e.byte.to+1-e.byte.from,e.status!==hd.NONE)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,r,a=t;const{type:o}=e.segmentReference;switch(o){case ud.BYTE_RANGE:s=e.segmentReference.url,r={from:ko(t,0).byte.from,to:ko(t,-1).byte.to};break;case ud.TEMPLATE:{const i=ko(t,0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),a=[i];break}default:n(o)}for(const t of a)t.status=hd.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,fedBytes:0,representationId:e.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await T(d,async function*(){const t=E(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),d.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:bd.PARAM,range:r,onProgress:(t,i)=>{if(!d.aborted)try{this.onSomeDataLoaded(t,e.id,r?r.from:0,i,d)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:d,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){var e;let i=!1;const r=this.getCurrentPosition();if(this.sourceBuffer&&s(r)){i=td(null===(e=this.sourceBuffer)||void 0===e?void 0:e.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,i||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,r){if(!this.activeSegments.size)return;const a=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=hd.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===hd.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=hd.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,u=t.byteLength;for(const o of this.activeSegments){const{segment:h}=o,l=d===ud.BYTE_RANGE,c=l?h.byte.to-h.byte.from+1:u;if(o.representationId!==e)continue;if(!(!l||h.byte.from>=i&&h.byte.to<i+t.byteLength))continue;if(r.aborted){a(o);continue}const p=l?h.byte.from-i:0,m=p<s,f=(l?h.byte.to-i:t.byteLength)<=s;if(h.status===hd.DOWNLOADING&&m&&f){h.status=hd.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,c);this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?n(o):a(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(c,s-p),o.loadedBytes>o.fedBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.fedBytes,o.loadedBytes-o.fedBytes),i=o.loadedBytes===c?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(h.status=hd.PARTIALLY_FED,o.fedBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,r).then((t=>{!t||r.aborted?a(o):o.fedBytes===c&&n(o)})))}}}abortSegment(t){t.status===hd.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=hd.NONE)),t.status=hd.NONE):t.status=hd.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 r=s instanceof Promise;e||(e=r),null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=pd((()=>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?T(this.destroyAbortController.signal,async function*(){const t=E(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,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,r),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',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=>{var e;a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;s+=i};for(const r of i){if(r.time.to>=e||s>=t)break;r.status===hd.FED&&d(r)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const r of i){if(r.time.from<e+this.forwardBufferTarget||s>t)break;r.status===hd.FED&&d(r)}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a/1e3,n/1e3)}abortBuffer(){this.sourceBuffer&&'open'===this.mediaSource.readyState&&this.sourceBufferTaskQueue.abort()}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),r=1e3*this.sourceBuffer.buffered.end(t);if(!(r<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&r>=i.time.to){e=void 0;break}r>i.time.from&&r<i.time.to&&(e.from=r),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=pd((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',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=1e3*this.sourceBuffer.buffered.start(e),s=1e3*this.sourceBuffer.buffered.end(e);t.push({from:i,to:s})}const e=this.tuning.dash.segmentTimelineTolerance;for(const i of this.segments.values())for(const s of i){const i=t.some((t=>t.from-e<=s.time.from&&t.to+e>=s.time.to));s.status!==hd.FED||i||(s.status=hd.NONE)}}}const Od=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='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},Bd=(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},Md=['timeupdate','progress','play','seeked','stalled'];var Ud,Vd;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Ud||(Ud={}));class qd{constructor(r){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new z(Ud.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.gapWatchdogStarted=!1,this.destroyController=new it,this.initManifest=T(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(Ud.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t})));if(!i)return null;let r;try{r=((t,e)=>{var i,r,a,n,o,d,u,h,l,c,p,m,f,v,g,S,b,y,T,E,w,$,k,A,P,D,_,R,I,L,C,x,N,O,B;const M={video:[],audio:[],text:[]},U=(new DOMParser).parseFromString(t,'application/xml').children[0],V=U.getElementsByTagName('Period')[0],q=V.children;let F;const H=U.getAttribute('mediaPresentationDuration'),G=V.getAttribute('duration');if(H)F=Od(H);else if(G){const t=Od(G);s(t)&&(F=t)}let Y=0;const z=null!==(r=null===(i=U.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==r?r:[],Q=z.includes(dd.WEBM_AS_IN_FFMPEG)||z.includes(dd.WEBM_AS_IN_SPEC)?ld.WEBM:ld.MP4;for(const t of q){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==i?void 0:i.split('/')[0],U=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],V=t.querySelectorAll('Representation');if('text'!==r)for(const a of V){const n=null!==(d=a.getAttribute('mimeType'))&&void 0!==d?d:i,o=null!==(h=null!==(u=a.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==h?h:'',V=null!==(c=null!==(l=a.getAttribute('contentType'))&&void 0!==l?l:null==n?void 0:n.split('/')[0])&&void 0!==c?c:r,q=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],H=parseInt(null!==(f=a.getAttribute('width'))&&void 0!==f?f:'',10),G=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),Q=parseInt(null!==(g=a.getAttribute('bandwidth'))&&void 0!==g?g:'',10)/1e3,j=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',W=null!==(b=a.getAttribute('quality'))&&void 0!==b?b:void 0,J=j?To(j):void 0,K=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(Y++).toString(10)}@${'video'===V?`${G}p`:'audio'===V?`${Q}Kbps`:o}`,X=null!==(w=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==w?w:'',Z=new URL(X,e).toString(),tt=[...z,...U,...q];let et;const it=a.querySelector('SegmentBase'),st=a.querySelector('SegmentTemplate');if(it){const t=null!==(k=null===($=a.querySelector('SegmentBase Initialization'))||void 0===$?void 0:$.getAttribute('range'))&&void 0!==k?k:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},r=null===(A=a.querySelector('SegmentBase'))||void 0===A?void 0:A.getAttribute('indexRange'),[n,o]=r?r.split('-').map((t=>parseInt(t,10))):[],d=r?{from:n,to:o}:void 0;et={type:ud.BYTE_RANGE,url:Z,initRange:s,indexRange:d}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(P=a.getAttribute('id'))&&void 0!==P?P:void 0,bandwidth:null!==(D=a.getAttribute('bandwidth'))&&void 0!==D?D:void 0},e=parseInt(null!==(_=st.getAttribute('timescale'))&&void 0!==_?_:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),r=null!==(L=parseInt(null!==(I=st.getAttribute('startNumber'))&&void 0!==I?I:'',10))&&void 0!==L?L:1,n=Bd(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(C=st.querySelectorAll('SegmentTimeline S'))&&void 0!==C?C:[],d=[];let u=r,h=0;for(const i of o){const r=1e3*parseInt(null!==(x=i.getAttribute('d'))&&void 0!==x?x:'',10),a=parseInt(null!==(N=i.getAttribute('r'))&&void 0!==N?N:'',10)||1,n=null!==(B=parseInt(null!==(O=i.getAttribute('t'))&&void 0!==O?O:'',10))&&void 0!==B?B:void 0;for(let i=0;i<a;i++){const i=Bd(s,{...t,segmentNumber:u.toString(10),segmentTime:n.toString(10)}),a=n?n/e:h;h+=r/e;const o=h;u++,d.push({time:{from:a,to:o},url:i})}}et={type:ud.TEMPLATE,baseUrl:Z,initUrl:n,segments:d}}}if(!V||!n)continue;const rt={video:od.VIDEO,audio:od.AUDIO,text:od.TEXT}[V];rt&&M[rt].push({id:K,kind:rt,segmentReference:et,profiles:tt,duration:F,bitrate:Q,mime:n,codecs:o,width:H,height:G,fps:J,quality:W})}}return{duration:F,container:Q,representations:M}})(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!r)return null;const a=({mime:e,codecs:i})=>{var s,r,a;return Boolean((null===(s=t.canPlayType)||void 0===s?void 0:s.call(t,e))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${e}; codecs="${i}"`)))};return this.manifest={...r,representations:no(Object.entries(r.representations).map((([t,e])=>[t,e.filter(a)])))},this.manifest.representations.video.length?this.state$.setState(Ud.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=T(this.destroyController.signal,async function*(t,e){c(this.manifest),c(this.element),this.state$.startTransitionTo(Ud.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 Nd(od.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new Nd(od.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=o(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),n=o(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(o(this.forceEnded$,y({allBuffersFull:r,someBufferEnded:n}).pipe(f((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var t;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(...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=>{var e;return null===(e=this.source)||void 0===e?void 0:e.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(Ud.REPRESENTATION_SELECTED),c(this.element),this.subscription.add(o(...Md.map((t=>a(this.element,t))),a(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(a(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(a(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&cd(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this)),this.tick=()=>{var t,e;if(!this.element||!this.videoBufferManager)return;const i=1e3*this.element.currentTime;this.videoBufferManager.maintain(i),null===(t=this.audioBufferManager)||void 0===t||t.maintain(i),!this.videoBufferManager.gaps.length&&!(null===(e=this.audioBufferManager)||void 0===e?void 0:e.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=w(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=r.throughputEstimator,this.tuning=r.tuning,this.fetcher=new yd({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(t,e){const i={[od.VIDEO]:this.videoBufferManager,[od.AUDIO]:this.audioBufferManager,[od.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}seek(t,e){var i,s,r,a,n;let o;c(this.element),c(this.videoBufferManager),o=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(null!==(i=this.videoBufferManager.findSegmentStartTime(t))&&void 0!==i?i:t,null!==(r=null===(s=this.audioBufferManager)||void 0===s?void 0:s.findSegmentStartTime(t))&&void 0!==r?r:t),cd(this.element.buffered,o)||(this.videoBufferManager.abort(),null===(a=this.audioBufferManager)||void 0===a||a.abort()),this.videoBufferManager.maintain(o),null===(n=this.audioBufferManager)||void 0===n||n.maintain(o),this.element.currentTime=o/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ud.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}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of this.bufferManagers)for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Vd||(Vd={}));const Fd=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?Vo(a):void 0)&&void 0!==n?n:G({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},Hd=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=ko(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:ko(t,-1)};class Gd{constructor(e){this.subscription=new i,this.videoState=new z(Vd.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new fo,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Lo,this.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&&(null==i?void 0:i.to)!==P.PAUSED&&t!==Vd.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===Vd.STOPPED)return this.videoState.startTransitionTo(Vd.READY),void this.prepare();switch(t){case Vd.READY:return void(e===P.PAUSED?(this.videoState.setState(Vd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Vd.PLAYING),this.playIfAllowed()));case Vd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Vd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Vd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Vd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==Vd.STOPPED&&(this.videoState.startTransitionTo(Vd.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(Vd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=e,this.video=vo(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(xo(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new qd({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=yo(this.video),r=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,r));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.playing$,t.firstFrameEvent$),n(i.canplay$,t.canplay$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(f(s),b(),v(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(co(this.video,e.isLooped,r)),this.subscription.add(po(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),n(No(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Vd.PLAYING),U(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(Vd.PAUSED),U(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Vd.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(f((({to:t})=>t===Ud.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Vd.READY)})));const d=e=>t.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:e});this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a(this.video,'progress')).subscribe((()=>{var i,s,r,a,n,o,u,h;const l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l===Ud.NONE||!this.videoTracks.length)return;const m=l===Ud.MANIFEST_LOADED&&!p,f=l===Ud.REPRESENTATION_SELECTED&&!p,v=e.autoVideoTrackSwitching.getState(),g=e.videoTrack.getState(),S=null===(i=this.videoTracks.find((({track:{id:t}})=>t===g)))||void 0===i?void 0:i.track,b=t.currentVideoTrack$.getValue(),y=td(this.video.buffered,1e3*this.video.currentTime),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),w=Math.max(S&&!v&&null!==(r=null===(s=this.audioRepresentations.get(S.id))||void 0===s?void 0:s.bitrate)&&void 0!==r?r:0,b&&null!==(n=null===(a=this.audioRepresentations.get(b.id))||void 0===a?void 0:a.bitrate)&&void 0!==n?n:0),$=Co(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:w,forwardBufferHealth:E,current:b,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),k=v?null!=$?$:S:null!=S?S:$;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),m){const t=k&&(null===(o=this.videoTracks.find((({track:t})=>t===k)))||void 0===o?void 0:o.representation);c(t),this.player.initRepresentations(t.id,null===(u=this.audioRepresentations.get(t.id))||void 0===u?void 0:u.id)}else if(f){const t=k&&(null===(h=this.videoTracks.find((({track:t})=>t===k)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(od.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(od.AUDIO,e.id).catch(d)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(l(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const m=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(m.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=Fd(t);if(s){this.videoTracks.push({track:s,representation:t});const r=Hd(e,i,t);r&&this.audioRepresentations.set(t.id,r)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){qo(this.video).then((t=>{t||(this.videoState.setState(Vd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Yd={};var zd;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(zd||(zd={}));const Qd=(t,e)=>new S((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class jd{constructor(t){this.subscription=new i,this.videoState=new z(zd.INITIALIZING),this.textTracksManager=new fo,this.trackLevels=new Map,this.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!==zd.INITIALIZING)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case zd.STOPPED:break;case zd.READY:case zd.PLAYING:case zd.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case zd.PLAYING:break;case zd.STOPPED:this.prepare();break;case zd.READY:case zd.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case zd.PAUSED:break;case zd.STOPPED:this.prepare();break;case zd.READY:this.videoState.setState(zd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case zd.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}},this.video=vo(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(xo(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.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',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Yd.Hls=e.default,Yd.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){c(Yd.Hls,'hls.js not loaded'),this.hls=new Yd.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(zd.STOPPED)}subscribe(){c(Yd.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=yo(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadStart$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),this.subscription.add(co(this.video,t.isLooped,i)),this.subscription.add(po(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qd(this.hls,Yd.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(zd.PLAYING),U(t.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(zd.PAUSED),U(t.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===zd.READY&&this.videoState.setState(zd.READY),this.videoState.getState()===zd.PLAYING&&this.playIfAllowed()}),i)),n(Qd(this.hls,Yd.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=Vo(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:G({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:u,level:e}),t.push(u),t}),[])))),e.availableVideoTracks$),n(Qd(this.hls,Yd.Events.LEVEL_LOADING).pipe(u((({url:t})=>xo(t)))),e.hostname$),this.subscription.add(lo(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 d=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},l=Qd(this.hls,Yd.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>d(this.hls.levels[t]))));l.pipe(f(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(lo(t.videoTrack,(()=>{var t;return null===(t=d(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),a=this.hls.currentLevel,n=this.hls.levels[a];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:l.pipe(u((t=>null==t?void 0:t.id))),onError:i})),n(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const m=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(m.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(zd.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(zd.PLAYING);await qo(this.video)||(this.videoState.setState(zd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(zd.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(zd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}}const Wd=t=>{let e=null;if(t.QUALITY&&(e=Vo(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=G({width:i,height:s})}return null!=e?e:null},Jd=async(t,e=t)=>{var i;const s=await et(t),r=(await s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=no(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=Wd(n);let u;n.BANDWIDTH&&(u=parseInt(n.BANDWIDTH,10)/1e3||void 0),!u&&n['AVERAGE-BANDWIDTH']&&(u=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let l;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(l={width:t,height:e})}const c=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:c,bandwidth:u,size:l,fps:h})}return a};var Kd,Xd,Zd,tu,eu,iu,su,ru,au,nu,ou,du,uu,hu,lu,cu,pu,mu,fu,vu;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Kd||(Kd={}));class gu{constructor(e){var s;this.subscription=new i,this.videoState=new z(Kd.STOPPED),this.textTracksManager=new fo,this.manifests$=new t([]),this.liveOffset=new go,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Kd.STOPPED&&(this.videoState.startTransitionTo(Kd.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(Kd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Kd.STOPPED)return this.videoState.startTransitionTo(Kd.READY),void this.prepare();if(s||r){const t=this.videoState.getState();return this.videoState.setState(Kd.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested)return this.videoState.startTransitionTo(Kd.READY),this.seek(a.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Kd.READY:return void(e===P.PAUSED?(this.videoState.setState(Kd.PAUSED),this.liveOffset.pause(),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Kd.PLAYING),this.playIfAllowed()));case Kd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Kd.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Kd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Kd.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())):(null==i?void 0:i.to)===P.PAUSED&&(U(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Kd.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=vo(e.container),this.params.output.element$.next(this.video);const r={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),Jd(M(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([r,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(xo(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(s=e.source.maxSeekBackTime)&&void 0!==s?s:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},r=yo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.ended$,t.endedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(po(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Kd.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Kd.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Kd.READY&&this.videoState.setState(Kd.READY),this.videoState.getState()===Kd.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(),r=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(xo(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Kd.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(f(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:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,h(['init'])).pipe(p(0));this.subscription.add(n.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=M(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),(async t=>{const e=await et(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0})(e).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){qo(this.video).then((t=>{t||(this.videoState.setState(Kd.PAUSED),this.liveOffset.pause(),U(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()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Xd||(Xd={}));class Su{constructor(e){this.subscription=new i,this.videoState=new z(Xd.STOPPED),this.textTracksManager=new fo,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Xd.STOPPED&&(this.videoState.startTransitionTo(Xd.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(Xd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Xd.STOPPED)return this.videoState.startTransitionTo(Xd.READY),void this.prepare();if(s||r){const t=this.videoState.getState();this.videoState.setState(Xd.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case Xd.READY:return void(e===P.PAUSED?(this.videoState.setState(Xd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Xd.PLAYING),this.playIfAllowed()));case Xd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Xd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Xd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Xd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));case Xd.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=vo(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(xo(this.params.source.url)),Jd(this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},r=yo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(co(this.video,e.isLooped,i)),this.subscription.add(po(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Xd.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Xd.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Xd.READY&&this.videoState.setState(Xd.READY),this.videoState.getState()===Xd.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(),r=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(xo(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Xd.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:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.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(){qo(this.video).then((t=>{t||(this.videoState.setState(Xd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Zd||(Zd={}));class bu{constructor(t){this.subscription=new i,this.videoState=new z(Zd.STOPPED),this.trackUrls={},this.textTracksManager=new fo,this.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!==Zd.STOPPED&&(this.videoState.startTransitionTo(Zd.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(Zd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(t===Zd.STOPPED)return this.videoState.startTransitionTo(Zd.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case Zd.READY:return void(e===P.PAUSED?(this.videoState.setState(Zd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Zd.PLAYING),this.playIfAllowed()));case Zd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Zd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Zd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Zd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}},this.params=t,this.video=vo(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.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},r=yo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(co(this.video,e.isLooped,i)),this.subscription.add(po(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Zd.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Zd.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Zd.READY&&this.videoState.setState(Zd.READY);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===Zd.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();c(i,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[i];c(s,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(s=uo(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(xo(s))}playIfAllowed(){qo(this.video).then((t=>{t||(this.videoState.setState(Zd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class yu{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 Tu=vd(),Eu=(null===(tu=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===tu?void 0:tu.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),wu=document.createElement('video'),$u={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(iu=null===(eu=window.SourceBuffer)||void 0===eu?void 0:eu.prototype)||void 0===iu?void 0:iu.appendBuffer)),hls:Boolean((null===(su=wu.canPlayType)||void 0===su?void 0:su.call(wu,'application/x-mpegurl'))||(null===(ru=wu.canPlayType)||void 0===ru?void 0:ru.call(wu,'vnd.apple.mpegURL')))},ku={mp4:Boolean(null===(au=wu.canPlayType)||void 0===au?void 0:au.call(wu,'video/mp4')),webm:Boolean(null===(nu=wu.canPlayType)||void 0===nu?void 0:nu.call(wu,'video/webm'))},Au={h264:Boolean(null===(du=null===(ou=window.MediaSource)||void 0===ou?void 0:ou.isTypeSupported)||void 0===du?void 0:du.call(ou,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(hu=null===(uu=window.MediaSource)||void 0===uu?void 0:uu.isTypeSupported)||void 0===hu?void 0:hu.call(uu,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(cu=null===(lu=window.MediaSource)||void 0===lu?void 0:lu.isTypeSupported)||void 0===cu?void 0:cu.call(lu,'video/webm; codecs="vp9"')),aac:Boolean(null===(mu=null===(pu=window.MediaSource)||void 0===pu?void 0:pu.isTypeSupported)||void 0===mu?void 0:mu.call(pu,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(vu=null===(fu=window.MediaSource)||void 0===fu?void 0:fu.isTypeSupported)||void 0===vu?void 0:vu.call(fu,'audio/webm; codecs="opus"'))},Pu=(Au.h264||Au.h265)&&Au.aac,Du=!Tu,_u=Eu||Tu,Ru=!$u.hls||!_u;const Iu=3e4,Lu=18e4,Cu=3,xu=100,Nu={cacheDuration:12e4},Ou={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Bu={maxPausedTime:3e4},Mu={maxPausedTime:3e4};class Uu{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.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)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,o=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new yu(o.filter((t=>s(r.sources[t]))).filter((t=>{switch(t){case D.DASH:return $u.mse&&ku.mp4&&Pu&&Du;case D.DASH_SEP:case D.DASH_SEP_VK:return $u.mse&&ku.mp4&&Pu;case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.DASH_LIVE_WEBM:return $u.mse&&ku.webm&&Au.vp9&&Au.opus;case D.DASH_LIVE:return $u.mse&&ku.mp4&&Pu;case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:return $u.mse&&ku.mp4&&Pu;case D.HLS:case D.HLS_LIVE:case D.HLS_ONDEMAND:return $u.hls&&ku.mp4&&_u;case D.HLS_JS:return $u.mse&&ku.mp4&&Pu&&Ru;case D.MPEG:return ku.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new yu(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}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',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();const t=this.current$.getValue().destination;c(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 r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case _.SCREEN:return this.createScreenProvider(e);case _.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r={container:i,source:null,desiredState:s,output:this.providerOutput,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case D.DASH:{const i=e[t];return c(i),new nd({...r,source:i,config:Nu})}case D.DASH_ONDEMAND_VK:case D.DASH_SEP_VK:case D.DASH_WEBM_VK:{const i=e[t];return c(i),new Gd({...r,source:i})}case D.DASH_SEP:case D.DASH_WEBM:case D.DASH_ONDEMAND:case D.DASH_LIVE_WEBM:{const i=e[t];return c(i),new Uo({...r,source:i,format:t,config:Mu})}case D.HLS:case D.HLS_ONDEMAND:{const i=e[t];return c(i),new Su({...r,source:i})}case D.HLS_LIVE:{const i=e[t];return c(i),new gu({...r,source:i,config:Bu})}case D.HLS_JS:{const i=e[t];return c(i),new jd({...r,source:i})}case D.MPEG:{const i=e[t];return c(i),new bu({...r,source:i})}case D.DASH_LIVE:{const i=e[t];return c(i),new Xo({...r,source:i,config:Ou})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return c(n),new j({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_.CHROMECAST:_.SCREEN}chooseFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.next();case _.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case _.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case _.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let t=[],r=0;const a=new i;var n;return a.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Iu,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(f((({type:t})=>void 0!==t)))},new S((t=>{const s=new i,r=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),a=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,l='unknown';return s.add(r.subscribe((t=>{h&&window.clearTimeout(h),l=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(a.subscribe((()=>{window.clearTimeout(h),l='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(l)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),a.add(this.providerError$.pipe($(xu,{leading:!1,trailing:!0})).subscribe((()=>{const e=Date.now();this.current$.getValue().destination===_.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(t[r])&&e<t[r]+Lu?(t=[],this.switchToNextProvider()):(t[r]=e,this.reinitProvider()),r=(r+1)%Cu}))),a}}const Vu=(t,e,i)=>i*e+(1-i)*t;class qu{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,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 s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ro(`raw_${s}`),this.smoothedSeries$=new Ro(`smoothed_${s}`),this.reportedSeries$=new Ro(`reported_${s}`),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=Vu(this.slow,t,this.params.emaAlphaSlow),this.fast=Vu(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 Fu;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Fu||(Fu={}));const Hu=new Map;let Gu=Fu.RUNTIME;const Yu=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Yu,'test'),localStorage.removeItem(Yu),Gu=Fu.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Yu),Gu=Fu.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Gu=Fu.RUNTIME}}})();const zu=(t,e)=>{switch(Gu){case Fu.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Fu.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Fu.RUNTIME:return void Hu.set(t,e);default:n(Gu)}},Qu=window.navigator.connection,ju=()=>{const t=null==Qu?void 0:Qu.downlink;if(s(t)&&10!==t)return 1e3*t},Wu=()=>{const t=null==Qu?void 0:Qu.rtt;if(s(t)&&3e3!==t)return t},Ju=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Ku{constructor(e){var r,n;this.subscription=new i,this.concurrentDownloads=new Set,this.tuningConfig=e;const o=Ku.load('one_video_throughput')||(e.useBrowserEstimation?ju():void 0)||5e3,d=null!==(n=null!==(r=Ku.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?Wu():void 0)&&void 0!==n?n:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(Ju(o,d,e.rttPenaltyRequestSize)),this.throughput=new qu({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new qu({initial:d,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=ju();t&&this.throughput.next(t);const e=Wu();s(e)&&this.rtt.next(e)};Qu&&'onchange'in Qu&&this.subscription.add(a(Qu,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{zu('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{zu('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(y({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>Ju(t,i,e.rttPenaltyRequestSize))),f((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=g();const r=new i;switch(this.subscription.add(r),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:r.add(a(t,'progress').pipe(b()).subscribe((t=>{e=t.loaded,s=g()})));break;case 1:case 0:r.add(a(t,'loadstart').subscribe((()=>{e=0,s=g()})))}r.add(a(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=g(),a=t-e,n=r-s;this.addRawSpeed(a,n,1)}this.concurrentDownloads.delete(t),r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=g();let r=0,a=g();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:u})=>{d?(this.addRawSpeed(i,g()-s,1),this.concurrentDownloads.delete(t)):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&g()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,g()-a,this.concurrentDownloads.size),r=0,a=g()),await(null==e?void 0:e.read().then(o,n)))};this.concurrentDownloads.add(t),null==e||e.read().then(o,n)}addRawSpeed(t,e,i=1){if(Ku.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){var e;const i=(t=>{var e,i;switch(Gu){case Fu.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case Fu.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case Fu.RUNTIME:return Hu.get(t);default:n(Gu)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const Xu={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:100},enableTelemetryAtStart:!1,formatsToAvoid:[D.DASH_WEBM,D.DASH_SEP,D.DASH_SEP_VK],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};const Zu=(t=(t=>t))=>({playbackState:e,seekState:s,playbackAbort$:a,looped$:n,position$:d})=>new S((h=>{let l;const c=e.transitionEnded$.pipe(f((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=e.stateChangeEnded$.pipe(f((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=s.stateChangeEnded$.pipe(f((({to:t})=>{var i,s;return t.state===C.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===P.PLAYING}))),v=s.stateChangeEnded$.pipe(f((({from:t,to:i})=>{var s,r;return t.state===C.Applying&&i.state===C.None&&(null!==(r=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:e.getState())===P.PLAYING}))),g=o(c,v).pipe(u((()=>t(d.getValue())))),S=o(o(p,m,a).pipe(u((()=>t(d.getValue())))),n.pipe(u(t)));return(new i).add(g.subscribe((e=>{l=t(e)}))).add(S.subscribe((e=>{const i=t(e);if(r(l)||l===i)return;const s={from:l,to:i};l=void 0,h.next(s)})))})),th=Zu((t=>t)),eh=Zu((t=>Math.round(1e3*t)+Date.now())),ih={[_.SCREEN]:{vod:[D.HLS,D.HLS_ONDEMAND,D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS_JS,D.MPEG],live:[D.HLS_LIVE,D.DASH_LIVE,D.DASH_LIVE_WEBM]},[_.CHROMECAST]:{vod:[D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS,D.HLS_ONDEMAND,D.MPEG],live:[D.HLS_LIVE]}};class sh{constructor(s={}){if(this.subscription=new i,this.logger=new k,this.isPlaybackStarted=!1,this.desiredState={playbackState:new z(P.STOPPED),seekState:new z({state:C.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),externalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({})},this.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({}),currentBuffer$:new t(void 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(R.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={inited$:new e,started$:new e,startAttempt$: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},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:Do},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Xu)){const s=Xu[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?{...s,...r}:null!=r?r:s}return e})(s),this.chromecastInitializer=new x({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ku(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)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(t){var e,i;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return c(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new Uu({screenFormatsPriority:[...ih[_.SCREEN].live,...ih[_.SCREEN].vod],chromecastFormatsPriority:[...ih[_.CHROMECAST].live,...ih[_.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},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(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.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),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===R.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()===R.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){c(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}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.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(){c(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(o(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.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$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(f((t=>t.to===P.PLAYING)),f((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=g(),this.events.inited$.next(),t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(f((t=>t.to===P.PLAYING||t.to===P.PAUSED)),p(0),b()).subscribe((t=>{const e=t.to===P.PLAYING,i=this.info.muted$.getValue(),s=e?i?I.SuccessWithoutSound:I.SuccessWithSound:I.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(f((t=>t.to===P.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).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()}})))}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}`,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)=>Y(t)?1:Y(e)?-1:q(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(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0: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}))).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})=>o(t.stateChangeEnded$.pipe(u((({to:t})=>{var e;return t.state===C.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),f(s)),e.pipe(f((()=>t.getState().state===C.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(v(!0)),e.providerOutput.seekedEvent$.pipe(v(!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',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(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(b(),u((()=>g()-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 n=new t(!0);this.subscription.add(e.current$.subscribe((()=>n.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(f((({to:t})=>t===P.PLAYING)),b()).subscribe((()=>n.next(!1))));let d=0;const h=o(e.providerOutput.isBuffering$,r,n).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=r.getValue()||n.getValue();return t&&!i})),l());this.subscription.add(h.subscribe((t=>{t?d=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(d),this.info.isStalled$.next(!1))})));const p=new i;this.subscription.add(p);const m=o(a(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(f((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(l()).subscribe((t=>{switch(c(this.providerContainer),p.unsubscribe(),t){case!0:p.add(eh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:m,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break;case!1:p.add(th({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:m,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=>null==t?void 0: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(f((t=>t.length>0)),b()).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=Co(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(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(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;c(this.providerContainer),c(e),Po={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Ao=t})),this.providerContainer.current$.subscribe((({type:t})=>_o('provider',t))),e.duration$.subscribe((t=>_o('duration',t))),e.availableVideoTracks$.pipe(f((t=>!!t.length)),b()).subscribe((t=>_o('tracks',t))),this.events.fatalError$.subscribe(new Ro('fatalError')),this.events.managedError$.subscribe(new Ro('managedError')),e.position$.subscribe(new Ro('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new Ro('quality')),e.currentBuffer$.subscribe(new Ro('buffer')),e.isBuffering$.subscribe(new Ro('isBuffering'))].forEach((t=>this.subscription.add(t))),_o('codecs',Object.keys(Au).filter((t=>Au[t])))}}const rh='@vkontakte/videoplayer-core@2.0.65';export{R as ChromecastState,L as HttpConnectionType,P as PlaybackState,sh as Player,rh as SDK_VERSION,I as StartStatus,D as VideoFormat,B as VideoQuality};
|
|
6
|
+
import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as r,fromEvent as a,assertNever as n,merge as o,tap as d,map as u,observableFrom as h,filterChanged as l,assertNonNullable as c,debounce as p,timeout as m,filter as f,mapTo as v,now as g,Observable as S,once as b,combine as y,abortable as T,getExponentialDelay as E,interval as w,throttle as $,Logger as k}from'@vkontakte/videoplayer-shared/es2018.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2018.esm.js';import A from'lodash/debounce';var P,D,_,R,I,L,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_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND_VK',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(D||(D={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(_||(_={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(R||(R={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(I||(I={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(L||(L={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(C||(C={}));class x{constructor(r){var a;this.connection$=new t(void 0),this.castState$=new t(R.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(R.NOT_AVAILABLE),this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const n='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${n}`}),r.isDisabled||!n)return;var o;s(null===(a=window.chrome)||void 0===a?void 0:a.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(o='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',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.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(a(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.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(t.sessionState)}}))).add(o(a(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),h([i.getCastState()])).pipe(l(),u(N),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var n;const o=a===R.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();c(s);const a=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(r(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===R.CONNECTED?s(this.connection$.getValue())?R.CONNECTED:R.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const N=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return R.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return R.AVAILABLE;case cast.framework.CastState.CONNECTING:return R.CONNECTING;case cast.framework.CastState.CONNECTED:return R.CONNECTED;default:return n(t)}};var O;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(O||(O={}));var B,M=(t,e=0,i=O.OFFSET_P)=>{switch(i){case O.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case O.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t},U=(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 V={[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}},q=(t,e)=>V[t].height>V[e].height,F=(t,e)=>V[t].height<V[e].height,H=Object.keys(V).sort(((t,e)=>F(t,e)?-1:1)),G=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return H.find((t=>{const e=V[t];return e.width>=s&&e.height>=i}))},Y=t=>t===B.INVARIANT;class z{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$),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 Q;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Q||(Q={}));class j{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new z(Q.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)if((null==s?void 0:s.to)===P.PAUSED||r.state!==C.Requested||t===Q.STOPPED)switch(i){case P.PLAYING:switch(t){case Q.PLAYING:break;case Q.PAUSED:case Q.READY:this.videoState.startTransitionTo(Q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Q.PLAYING:this.videoState.startTransitionTo(Q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Q.PAUSED:break;case Q.READY:this.videoState.startTransitionTo(Q.PAUSED),this.videoState.setState(Q.PAUSED);break;case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();break;default:n(t)}break;default:n(i)}else this.seek(r.position)}else t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.stop())},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 D.MPEG:case D.DASH:case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.HLS:case D.HLS_JS:case D.HLS_ONDEMAND:return!1;case D.HLS_LIVE:case D.DASH_LIVE:case D.DASH_LIVE_WEBM:return!0;default:return n(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(o(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(p(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(a(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(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(a(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(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),U(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:n(i)}})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(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(Q.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(Q.PLAYING),U(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(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Q.PAUSED&&t!==Q.PLAYING||(this.videoState.setState(Q.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Q.PLAYING&&t!==Q.PAUSED||(this.videoState.setState(Q.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Q.READY&&this.videoState.setState(Q.READY)}handleRemoteStop(){this.videoState.getState()!==Q.STOPPED&&this.videoState.setState(Q.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}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){var e;const i=this.params.source;let r,a,o;switch(t){case D.MPEG:{const e=i[t];c(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===B.INVARIANT?1:e===B.INVARIANT?-1:F(t,e)?1:-1))[0];c(s);const n=e[s];c(n),r=n,a='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS:case D.HLS_ONDEMAND:{const e=i[t];c(e),r=e.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM_VK:case D.DASH_WEBM:{const e=i[t];c(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS_LIVE:{const e=i[t];c(e),r=M(e.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case D.DASH_LIVE_WEBM:{const e=i[t];c(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case D.HLS_JS:case D.DASH:case D.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return n(t)}const d=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:r,a);d.contentUrl=r,d.streamType=o,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:h}=this.params.meta;return s(u)&&(d.metadata.title=u),s(h)&&(d.metadata.subtitle=h),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(m(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',message:e,thrown:t})})).finally((()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}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 K{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&&(K.prototype[Symbol.toStringTag]='AbortController',J.prototype[Symbol.toStringTag]='AbortSignal');const Z=X({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),tt=Z?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!X({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty('signal')||r)&&(a=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const r=new i(t,e);return s&&Object.defineProperty(r,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),r},a.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=a&&a.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 r=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,n(t,e)])}return n(t,e)},Request:a}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=Z?tt.fetch:window.fetch;Z?tt.Request:window.Request;const it=Z?K:window.AbortController,st=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class rt{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}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[r,a]=st(s.request);if(r>=i.from&&a<=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){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),r=this.activeRequests.get(i.url);s&&r&&r.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(st),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 a=new URL(t,location.href);a.searchParams.append('bytes',`${s}-${r}`);const n=a.toString(),o=new it,d=o.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return et(n,{signal:d}).then((t=>{var e,i,a;if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const d=n.getReader(),l=parseInt(null!==(a=t.headers.get('Content-Length'))&&void 0!==a?a:'',10)||r-s+1;u.data=new ArrayBuffer(l);const c=new Uint8Array(u.data),p=async({done:t,value:e})=>{t?this.onBigRequestProgress(u):e&&(c.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),await(null==d?void 0:d.read().then(p,rt.suppressStreamErrors).catch(h)))};null==d||d.read().then(p,rt.suppressStreamErrors).catch(h)}),rt.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,d,u,h,l,c,p;if(!this.activeRequests.has(t)||!r)return;const m=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of m){const{request:m}=n,[f,v]=st(m),g=f>=e&&v<=e+s,S=e>=f&&e+s<v,b=r.slice(f-e,Math.min(v-e+1,s));if((g||S)&&(m.requestStartDate=null!==(o=m.requestStartDate)&&void 0!==o?o:new Date,m.firstByteDate=null!==(d=m.firstByteDate)&&void 0!==d?d:new Date,m.bytesLoaded=b.byteLength,m.bytesTotal=i-e),g){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==n))),null===(h=n.success)||void 0===h||h.call(n,b,'',t);const e=a?Array.from(a.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(m,t,null!==(c=null==a?void 0:a.status)&&void 0!==c?c:200,e,[])}else S&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var r,a,n,o;if(null===(a=(r=this.params).onError)||void 0===a||a.call(r,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const d=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of d){const[r,a]=st(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(o=null==t?void 0:t.error)||void 0===o||o.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=st(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.call(t,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{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 nt=(t,e)=>{const i=new rt(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new at(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var ot=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},dt='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},ut=function(t){try{return!!t()}catch(t){return!0}},ht=!ut((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),lt=ht,ct=Function.prototype,pt=ct.bind,mt=ct.call,ft=lt&&pt.bind(mt,mt),vt=lt?function(t){return t&&ft(t)}:function(t){return t&&function(){return mt.apply(t,arguments)}},gt=vt,St=gt({}.toString),bt=gt(''.slice),yt=function(t){return bt(St(t),8,-1)},Tt=ut,Et=yt,wt=Object,$t=vt(''.split),kt=Tt((function(){return!wt('z').propertyIsEnumerable(0)}))?function(t){return'String'==Et(t)?$t(t,''):wt(t)}:wt,At=TypeError,Pt=function(t){if(null==t)throw At('Can\'t call method on '+t);return t},Dt=kt,_t=Pt,Rt=function(t){return Dt(_t(t))},It={},Lt=function(t){return t&&t.Math==Math&&t},Ct=Lt('object'==typeof globalThis&&globalThis)||Lt('object'==typeof window&&window)||Lt('object'==typeof self&&self)||Lt('object'==typeof dt&&dt)||function(){return this}()||Function('return this')(),xt=function(t){return'function'==typeof t},Nt=Ct,Ot=Object.defineProperty,Bt=function(t,e){try{Ot(Nt,t,{value:e,configurable:!0,writable:!0})}catch(i){Nt[t]=e}return e},Mt=Ct['__core-js_shared__']||Bt('__core-js_shared__',{}),Ut=xt,Vt=Mt,qt=vt(Function.toString);Ut(Vt.inspectSource)||(Vt.inspectSource=function(t){return qt(t)});var Ft,Ht,Gt=xt,Yt=Vt.inspectSource,zt=Ct.WeakMap,Qt=Gt(zt)&&/native code/.test(Yt(zt)),jt=xt,Wt=function(t){return'object'==typeof t?null!==t:jt(t)},Jt=!ut((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Kt={},Xt=Wt,Zt=Ct.document,te=Xt(Zt)&&Xt(Zt.createElement),ee=function(t){return te?Zt.createElement(t):{}},ie=ee,se=!Jt&&!ut((function(){return 7!=Object.defineProperty(ie('div'),'a',{get:function(){return 7}}).a})),re=Jt&&ut((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),ae=Wt,ne=String,oe=TypeError,de=function(t){if(ae(t))return t;throw oe(ne(t)+' is not an object')},ue=ht,he=Function.prototype.call,le=ue?he.bind(he):function(){return he.apply(he,arguments)},ce={},pe=ce,me=Ct,fe=xt,ve=function(t){return fe(t)?t:void 0},ge=function(t,e){return arguments.length<2?ve(pe[t])||ve(me[t]):pe[t]&&pe[t][e]||me[t]&&me[t][e]},Se=vt({}.isPrototypeOf),be=Ct,ye=ge('navigator','userAgent')||'',Te=be.process,Ee=be.Deno,we=Te&&Te.versions||Ee&&Ee.version,$e=we&&we.v8;$e&&(Ht=(Ft=$e.split('.'))[0]>0&&Ft[0]<4?1:+(Ft[0]+Ft[1])),!Ht&&ye&&(!(Ft=ye.match(/Edge\/(\d+)/))||Ft[1]>=74)&&(Ft=ye.match(/Chrome\/(\d+)/))&&(Ht=+Ft[1]);var ke=Ht,Ae=ut,Pe=!!Object.getOwnPropertySymbols&&!Ae((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&ke&&ke<41})),De=Pe&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,_e=ge,Re=xt,Ie=Se,Le=Object,Ce=De?function(t){return'symbol'==typeof t}:function(t){var e=_e('Symbol');return Re(e)&&Ie(e.prototype,Le(t))},xe=String,Ne=function(t){try{return xe(t)}catch(t){return'Object'}},Oe=xt,Be=Ne,Me=TypeError,Ue=function(t){if(Oe(t))return t;throw Me(Be(t)+' is not a function')},Ve=Ue,qe=function(t,e){var i=t[e];return null==i?void 0:Ve(i)},Fe=le,He=xt,Ge=Wt,Ye=TypeError,ze={exports:{}},Qe=Mt;(ze.exports=function(t,e){return Qe[t]||(Qe[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.24.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE',source:'https://github.com/zloirock/core-js'});var je=Pt,We=Object,Je=function(t){return We(je(t))},Ke=Je,Xe=vt({}.hasOwnProperty),Ze=Object.hasOwn||function(t,e){return Xe(Ke(t),e)},ti=vt,ei=0,ii=Math.random(),si=ti(1..toString),ri=function(t){return'Symbol('+(void 0===t?'':t)+')_'+si(++ei+ii,36)},ai=Ct,ni=ze.exports,oi=Ze,di=ri,ui=Pe,hi=De,li=ni('wks'),ci=ai.Symbol,pi=ci&&ci.for,mi=hi?ci:ci&&ci.withoutSetter||di,fi=function(t){if(!oi(li,t)||!ui&&'string'!=typeof li[t]){var e='Symbol.'+t;ui&&oi(ci,t)?li[t]=ci[t]:li[t]=hi&&pi?pi(e):mi(e)}return li[t]},vi=le,gi=Wt,Si=Ce,bi=qe,yi=function(t,e){var i,s;if('string'===e&&He(i=t.toString)&&!Ge(s=Fe(i,t)))return s;if(He(i=t.valueOf)&&!Ge(s=Fe(i,t)))return s;if('string'!==e&&He(i=t.toString)&&!Ge(s=Fe(i,t)))return s;throw Ye('Can\'t convert object to primitive value')},Ti=TypeError,Ei=fi('toPrimitive'),wi=function(t,e){if(!gi(t)||Si(t))return t;var i,s=bi(t,Ei);if(s){if(void 0===e&&(e='default'),i=vi(s,t,e),!gi(i)||Si(i))return i;throw Ti('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),yi(t,e)},$i=Ce,ki=function(t){var e=wi(t,'string');return $i(e)?e:e+''},Ai=Jt,Pi=se,Di=re,_i=de,Ri=ki,Ii=TypeError,Li=Object.defineProperty,Ci=Object.getOwnPropertyDescriptor;Kt.f=Ai?Di?function(t,e,i){if(_i(t),e=Ri(e),_i(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Ci(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Li(t,e,i)}:Li:function(t,e,i){if(_i(t),e=Ri(e),_i(i),Pi)try{return Li(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Ii('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var xi,Ni,Oi,Bi=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},Mi=Kt,Ui=Bi,Vi=Jt?function(t,e,i){return Mi.f(t,e,Ui(1,i))}:function(t,e,i){return t[e]=i,t},qi=ze.exports,Fi=ri,Hi=qi('keys'),Gi=function(t){return Hi[t]||(Hi[t]=Fi(t))},Yi={},zi=Qt,Qi=Ct,ji=vt,Wi=Wt,Ji=Vi,Ki=Ze,Xi=Mt,Zi=Gi,ts=Yi,es=Qi.TypeError,is=Qi.WeakMap;if(zi||Xi.state){var ss=Xi.state||(Xi.state=new is),rs=ji(ss.get),as=ji(ss.has),ns=ji(ss.set);xi=function(t,e){if(as(ss,t))throw new es('Object already initialized');return e.facade=t,ns(ss,t,e),e},Ni=function(t){return rs(ss,t)||{}},Oi=function(t){return as(ss,t)}}else{var os=Zi('state');ts[os]=!0,xi=function(t,e){if(Ki(t,os))throw new es('Object already initialized');return e.facade=t,Ji(t,os,e),e},Ni=function(t){return Ki(t,os)?t[os]:{}},Oi=function(t){return Ki(t,os)}}var ds={set:xi,get:Ni,has:Oi,enforce:function(t){return Oi(t)?Ni(t):xi(t,{})},getterFor:function(t){return function(e){var i;if(!Wi(e)||(i=Ni(e)).type!==t)throw es('Incompatible receiver, '+t+' required');return i}}},us=ht,hs=Function.prototype,ls=hs.apply,cs=hs.call,ps='object'==typeof Reflect&&Reflect.apply||(us?cs.bind(ls):function(){return cs.apply(ls,arguments)}),ms={},fs={},vs={}.propertyIsEnumerable,gs=Object.getOwnPropertyDescriptor,Ss=gs&&!vs.call({1:2},1);fs.f=Ss?function(t){var e=gs(this,t);return!!e&&e.enumerable}:vs;var bs=Jt,ys=le,Ts=fs,Es=Bi,ws=Rt,$s=ki,ks=Ze,As=se,Ps=Object.getOwnPropertyDescriptor;ms.f=bs?Ps:function(t,e){if(t=ws(t),e=$s(e),As)try{return Ps(t,e)}catch(t){}if(ks(t,e))return Es(!ys(Ts.f,t,e),t[e])};var Ds=ut,_s=xt,Rs=/#|\.prototype\./,Is=function(t,e){var i=Cs[Ls(t)];return i==Ns||i!=xs&&(_s(e)?Ds(e):!!e)},Ls=Is.normalize=function(t){return String(t).replace(Rs,'.').toLowerCase()},Cs=Is.data={},xs=Is.NATIVE='N',Ns=Is.POLYFILL='P',Os=Is,Bs=Ue,Ms=ht,Us=vt(vt.bind),Vs=function(t,e){return Bs(t),void 0===e?t:Ms?Us(t,e):function(){return t.apply(e,arguments)}},qs=Ct,Fs=ps,Hs=vt,Gs=xt,Ys=ms.f,zs=Os,Qs=ce,js=Vs,Ws=Vi,Js=Ze,Ks=function(t){var e=function(i,s,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,r)}return Fs(t,this,arguments)};return e.prototype=t.prototype,e},Xs=function(t,e){var i,s,r,a,n,o,d,u,h=t.target,l=t.global,c=t.stat,p=t.proto,m=l?qs:c?qs[h]:(qs[h]||{}).prototype,f=l?Qs:Qs[h]||Ws(Qs,h,{})[h],v=f.prototype;for(r in e)i=!zs(l?r:h+(c?'.':'#')+r,t.forced)&&m&&Js(m,r),n=f[r],i&&(o=t.dontCallGetSet?(u=Ys(m,r))&&u.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?js(a,qs):t.wrap&&i?Ks(a):p&&Gs(a)?Hs(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Ws(d,'sham',!0),Ws(f,r,d),p&&(Js(Qs,s=h+'Prototype')||Ws(Qs,s,{}),Ws(Qs[s],r,a),t.real&&v&&!v[r]&&Ws(v,r,a)))},Zs=Jt,tr=Ze,er=Function.prototype,ir=Zs&&Object.getOwnPropertyDescriptor,sr=tr(er,'name'),rr={EXISTS:sr,PROPER:sr&&'something'===function(){}.name,CONFIGURABLE:sr&&(!Zs||Zs&&ir(er,'name').configurable)},ar={},nr=Math.ceil,or=Math.floor,dr=Math.trunc||function(t){var e=+t;return(e>0?or:nr)(e)},ur=function(t){var e=+t;return e!=e||0===e?0:dr(e)},hr=ur,lr=Math.max,cr=Math.min,pr=ur,mr=Math.min,fr=function(t){return t>0?mr(pr(t),9007199254740991):0},vr=function(t){return fr(t.length)},gr=Rt,Sr=function(t,e){var i=hr(t);return i<0?lr(i+e,0):cr(i,e)},br=vr,yr=function(t){return function(e,i,s){var r,a=gr(e),n=br(a),o=Sr(s,n);if(t&&i!=i){for(;n>o;)if((r=a[o++])!=r)return!0}else for(;n>o;o++)if((t||o in a)&&a[o]===i)return t||o||0;return!t&&-1}},Tr={includes:yr(!0),indexOf:yr(!1)},Er=Ze,wr=Rt,$r=Tr.indexOf,kr=Yi,Ar=vt([].push),Pr=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Dr=function(t,e){var i,s=wr(t),r=0,a=[];for(i in s)!Er(kr,i)&&Er(s,i)&&Ar(a,i);for(;e.length>r;)Er(s,i=e[r++])&&(~$r(a,i)||Ar(a,i));return a},_r=Pr,Rr=Object.keys||function(t){return Dr(t,_r)},Ir=Jt,Lr=re,Cr=Kt,xr=de,Nr=Rt,Or=Rr;ar.f=Ir&&!Lr?Object.defineProperties:function(t,e){xr(t);for(var i,s=Nr(e),r=Or(e),a=r.length,n=0;a>n;)Cr.f(t,i=r[n++],s[i]);return t};var Br,Mr=ge('document','documentElement'),Ur=de,Vr=ar,qr=Pr,Fr=Yi,Hr=Mr,Gr=ee,Yr=Gi('IE_PROTO'),zr=function(){},Qr=function(t){return'<script>'+t+'<\/script>'},jr=function(t){t.write(Qr('')),t.close();var e=t.parentWindow.Object;return t=null,e},Wr=function(){try{Br=new ActiveXObject('htmlfile')}catch(t){}var t,e;Wr='undefined'!=typeof document?document.domain&&Br?jr(Br):((e=Gr('iframe')).style.display='none',Hr.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Qr('document.F=Object')),t.close(),t.F):jr(Br);for(var i=qr.length;i--;)delete Wr.prototype[qr[i]];return Wr()};Fr[Yr]=!0;var Jr,Kr,Xr,Zr=Object.create||function(t,e){var i;return null!==t?(zr.prototype=Ur(t),i=new zr,zr.prototype=null,i[Yr]=t):i=Wr(),void 0===e?i:Vr.f(i,e)},ta=!ut((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ea=Ze,ia=xt,sa=Je,ra=ta,aa=Gi('IE_PROTO'),na=Object,oa=na.prototype,da=ra?na.getPrototypeOf:function(t){var e=sa(t);if(ea(e,aa))return e[aa];var i=e.constructor;return ia(i)&&e instanceof i?i.prototype:e instanceof na?oa:null},ua=Vi,ha=function(t,e,i,s){return s&&s.enumerable?t[e]=i:ua(t,e,i),t},la=ut,ca=xt,pa=Zr,ma=da,fa=ha,va=fi('iterator'),ga=!1;[].keys&&('next'in(Xr=[].keys())?(Kr=ma(ma(Xr)))!==Object.prototype&&(Jr=Kr):ga=!0);var Sa=null==Jr||la((function(){var t={};return Jr[va].call(t)!==t}));ca((Jr=Sa?{}:pa(Jr))[va])||fa(Jr,va,(function(){return this}));var ba={IteratorPrototype:Jr,BUGGY_SAFARI_ITERATORS:ga},ya={};ya[fi('toStringTag')]='z';var Ta='[object z]'===String(ya),Ea=Ta,wa=xt,$a=yt,ka=fi('toStringTag'),Aa=Object,Pa='Arguments'==$a(function(){return arguments}()),Da=Ea?$a:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=Aa(t),ka))?i:Pa?$a(e):'Object'==(s=$a(e))&&wa(e.callee)?'Arguments':s},_a=Da,Ra=Ta?{}.toString:function(){return'[object '+_a(this)+']'},Ia=Ta,La=Kt.f,Ca=Vi,xa=Ze,Na=Ra,Oa=fi('toStringTag'),Ba=function(t,e,i,s){if(t){var r=i?t:t.prototype;xa(r,Oa)||La(r,Oa,{configurable:!0,value:e}),s&&!Ia&&Ca(r,'toString',Na)}},Ma=ba.IteratorPrototype,Ua=Zr,Va=Bi,qa=Ba,Fa=It,Ha=function(){return this},Ga=(TypeError,vt);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Ga(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Ya=Xs,za=le,Qa=function(t,e,i,s){var r=e+' Iterator';return t.prototype=Ua(Ma,{next:Va(+!s,i)}),qa(t,r,!1,!0),Fa[r]=Ha,t},ja=da,Wa=Ba,Ja=ha,Ka=It,Xa=rr.PROPER,Za=ba.BUGGY_SAFARI_ITERATORS,tn=fi('iterator'),en=function(){return this},sn=Rt,rn=It,an=ds;Kt.f;var nn=function(t,e,i,s,r,a,n){Qa(i,e,s);var o,d,u,h=function(t){if(t===r&&f)return f;if(!Za&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},l=e+' Iterator',c=!1,p=t.prototype,m=p[tn]||p['@@iterator']||r&&p[r],f=!Za&&m||h(r),v='Array'==e&&p.entries||m;if(v&&(o=ja(v.call(new t)))!==Object.prototype&&o.next&&(Wa(o,l,!0,!0),Ka[l]=en),Xa&&'values'==r&&m&&'values'!==m.name&&(c=!0,f=function(){return za(m,this)}),r)if(d={values:h('values'),keys:a?f:h('keys'),entries:h('entries')},n)for(u in d)(Za||c||!(u in p))&&Ja(p,u,d[u]);else Ya({target:e,proto:!0,forced:Za||c},d);return n&&p[tn]!==f&&Ja(p,tn,f,{name:r}),Ka[e]=f,d},on=an.set,dn=an.getterFor('Array Iterator');nn(Array,'Array',(function(t,e){on(this,{type:'Array Iterator',target:sn(t),index:0,kind:e})}),(function(){var t=dn(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),rn.Arguments=rn.Array;var un=It,hn=fi('iterator'),ln=Array.prototype,cn=Da,pn=qe,mn=It,fn=fi('iterator'),vn=function(t){if(null!=t)return pn(t,fn)||pn(t,'@@iterator')||mn[cn(t)]},gn=le,Sn=Ue,bn=de,yn=Ne,Tn=vn,En=TypeError,wn=le,$n=de,kn=qe,An=Vs,Pn=le,Dn=de,_n=Ne,Rn=function(t){return void 0!==t&&(un.Array===t||ln[hn]===t)},In=vr,Ln=Se,Cn=function(t,e){var i=arguments.length<2?Tn(t):e;if(Sn(i))return bn(gn(i,t));throw En(yn(t)+' is not iterable')},xn=vn,Nn=function(t,e,i){var s,r;$n(t);try{if(!(s=kn(t,'return'))){if('throw'===e)throw i;return i}s=wn(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return $n(s),i},On=TypeError,Bn=function(t,e){this.stopped=t,this.result=e},Mn=Bn.prototype,Un=ki,Vn=Kt,qn=Bi,Fn=function(t,e,i){var s,r,a,n,o,d,u,h=i&&i.that,l=!(!i||!i.AS_ENTRIES),c=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=An(e,h),v=function(t){return s&&Nn(s,'normal',t),new Bn(!0,t)},g=function(t){return l?(Dn(t),m?f(t[0],t[1],v):f(t[0],t[1])):m?f(t,v):f(t)};if(c)s=t.iterator;else if(p)s=t;else{if(!(r=xn(t)))throw On(_n(t)+' is not iterable');if(Rn(r)){for(a=0,n=In(t);n>a;a++)if((o=g(t[a]))&&Ln(Mn,o))return o;return new Bn(!1)}s=Cn(t,r)}for(d=c?t.next:s.next;!(u=Pn(d,s)).done;){try{o=g(u.value)}catch(t){Nn(s,'throw',t)}if('object'==typeof o&&o&&Ln(Mn,o))return o}return new Bn(!1)},Hn=function(t,e,i){var s=Un(e);s in t?Vn.f(t,s,qn(0,i)):t[s]=i};Xs({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Fn(t,(function(t,i){Hn(e,t,i)}),{AS_ENTRIES:!0}),e}});var Gn=ce.Object.fromEntries,Yn={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},zn=Ct,Qn=Da,jn=Vi,Wn=It,Jn=fi('toStringTag');for(var Kn in Yn){var Xn=zn[Kn],Zn=Xn&&Xn.prototype;Zn&&Qn(Zn)!==Jn&&jn(Zn,Jn,Kn),Wn[Kn]=Wn.Array}var to=Gn,eo=i=>{const r=new t(1/0),a=new e,n=new t(void 0),o=new t(void 0);let d=NaN,u=!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=>{var e,i,a,d,u;const h=to(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in h||'x-playback-duration-millis'in h){const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)}const l=null!==(d=h['x-delivery-type'])&&void 0!==d?d:L.HTTP1,c=null!==(u={1:!0,0:!1}[h['x-reused']])&&void 0!==u?u:void 0;n.next(l),o.next(c)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!u&&(u=!0,a.next(Date.now()-d)),i(...t)},d=Date.now(),u=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a,connectionReused$:o,connectionType$:n}},io=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},so=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 ro=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),u=e(),h=r(n),l=new i;return n&&l.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(u,d)||(s(d),h&&t.setState(d)),l.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),h&&t.setState(e.to)}),o)),l},ao=(t,e,i)=>ro(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),no=(t,e,i,r)=>ro(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),oo=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class uo{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',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(ro(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(ro(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(ro(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){c(this.video);const{textTracks:t}=this.video;this.subscription.add(a(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(a(t,'addtrack'),a(t,'removetrack'),h(['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(o(a(t,'change'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),l()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(a(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(a(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.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){c(this.video);const e=[...this.video.textTracks];return t?e:e.filter(uo.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){c(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&oo(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){c(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){c(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 ho=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class lo{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){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}}class co{constructor(t){this._buffer=[],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:r})=>{const a=s>=t&&s<e,n=r>=t&&r<e;a&&n||(a?i(e,r):n?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var po=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const n=t.start(a),o=t.end(a);if(n<=e&&e<=o){if(s=n,r=o,!i)return{from:s,to:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{from:s,to:r}};const mo=t=>{const i=e=>a(t,e).pipe(v(void 0)),r=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>a(t,e)))).pipe(u((()=>t.readyState<3)),l()),n=o(a(t,'progress'),a(t,'timeupdate')).pipe(u((()=>po(t.buffered,t.currentTime)))),d=a(t,'volumechange').pipe(p(0),u((()=>({muted:t.muted,volume:t.volume})))),h=a(t,'error').pipe(u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),c=a(t,'timeupdate').pipe(u((()=>t.currentTime))),m=new e;let g;return c.subscribe((e=>{t.loop&&s(g)&&s(e)&&g>=t.duration-.3&&e<=.3&&m.next(g),g=e})),{playing$:i('playing'),pause$:i('pause').pipe(f((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:m,error$:h,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:c,durationChange$:a(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:r,currentBuffer$:n,volumeState$:d}},fo=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var vo=Je,go=vr,So=ur;Xs({target:'Array',proto:!0},{at:function(t){var e=vo(this),i=go(e),s=So(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var bo=ge('Array','at');let yo=!1,To={};const Eo=t=>{t(To)},wo=(t,e)=>{var i;yo&&(To.meta=null!==(i=To.meta)&&void 0!==i?i:{},To.meta[t]=e)};class $o{constructor(t){this.name=t}next(t){var e,i;if(!yo)return;To.series=null!==(e=To.series)&&void 0!==e?e:{};const s=null!==(i=To.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),To.series[this.name]=s}}const ko=new $o('best_bitrate');class Ao{constructor(){this.history={}}recordSelection(t){this.history[t.id]=g()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Po=(t,{container:e,throughput:i,tuning:a,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:u,current:h,history:l})=>{var c,p,m,f;const v=a.usePixelRatio&&null!==(c=window.devicePixelRatio)&&void 0!==c?c:1,S=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*a.containerSizeFactor,height:e.height*v*a.containerSizeFactor},b=S&&G(S),y=a.considerPlaybackRate&&s(u)?u:1,T=t.filter((t=>!Y(t.quality))).sort(((t,e)=>q(t.quality,e.quality)?-1:1)),E=null===(p=bo(T,-1))||void 0===p?void 0:p.quality,w=null===(m=bo(T,0))||void 0===m?void 0:m.quality,$=r(n)||s(n.min)&&s(n.max)&&F(n.max,n.min)||s(n.min)&&w&&q(n.min,w)||s(n.max)&&E&&F(n.max,E),k=y*(A=null!=d?d:.5,P=a.bitrateFactorAtEmptyBuffer,D=a.bitrateFactorAtFullBuffer,(P-D)*Math.pow(2,-10*A)+D);var A,P,D;const _=T.filter((t=>{const e=!b||F(t.quality,b),u=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*k,l=a.lazyQualitySwitch&&s(a.minBufferToSwitchUp)&&h&&!Y(h.quality)&&(null!=d?d:0)<a.minBufferToSwitchUp&&q(t.quality,h.quality),c=$||(r(n.max)||(p=t.quality,m=n.max,V[p].height<=V[m].height))&&(r(n.min)||((t,e)=>V[t].height>=V[e].height)(t.quality,n.min));var p,m;return e&&u&&!l&&c}))[0];_&&_.bitrate&&ko.next(_.bitrate);const R=null!==(f=null!=_?_:T[Math.ceil((T.length-1)/2)])&&void 0!==f?f:t[0],I=R&&l&&l.history[R.id]&&g()-l.history[R.id]<=a.trackCooldown&&(!l.last||R.id!==l.last.id);if((null==R?void 0:R.id)&&l&&!I&&l.recordSelection(R),I&&(null==l?void 0:l.last)){const t=l.last;return null==l||l.recordSwitch(t),t}return null==l||l.recordSwitch(R),R};var Do=t=>new URL(t).hostname;const _o=(t,e=300)=>new S((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()})),Ro={};var Io;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Io||(Io={}));const Lo=(t,e)=>new S((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Co{constructor(e){this.subscription=new i,this.videoState=new z(Io.DOWNLOADING_LIB),this.textTracksManager=new uo,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new lo,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==Io.DOWNLOADING_LIB&&t!==Io.STREAM_INITIALIZED)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&t!==Io.STOPPED&&e!==P.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case Io.STOPPED:break;case Io.PLAYING:case Io.PAUSED:case Io.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Io.PLAYING:break;case Io.PAUSED:r&&(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 Io.READY:this.play();break;case Io.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Io.PLAYING:this.pause(),this.liveOffset.pause();break;case Io.PAUSED:break;case Io.READY:this.videoState.setState(Io.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Io.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}},this.video=ho(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Ro.MediaPlayer=e.MediaPlayer,Ro.Debug=e.Debug,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){c(Ro.MediaPlayer,'dashjs not loaded'),c(Ro.Debug,'dashjs not loaded'),this.player=Ro.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?fo(t.frameRate+''):void 0),!0)));(this.params.format===D.DASH_WEBM||this.params.format===D.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=nt(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&&so(this.player),ot(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:io})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Io.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(_o(this.video),this.elementSize$),a(Lo(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$),a(Lo(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Lo(this.player,'qualityChangeRendered').pipe(f((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));n.pipe(f(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(f((({to:t})=>t===Io.STREAM_INITIALIZED)),b()).subscribe((()=>{this.subscription.add(ro(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:n.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add(ro(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),a(Lo(this.player,'bufferStateChanged').pipe(f((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),a(Lo(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type'))&&void 0!==s?s:L.HTTP1,d=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(d),t.hostname$.next(Do(i))})),a(Lo(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 r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=G(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===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(Io.STREAM_INITIALIZED),this.videoState.startTransitionTo(Io.READY)})),a(Lo(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)})),a(o(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=Po(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));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(f(s))}).pipe(f((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=Lo(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));a(y({availableFrom:this.availableFrom$.pipe(f(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(d.pipe(f((()=>!1===this.isLive$.getValue()))),t.position$),a(Lo(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Lo(this.player,'playbackEnded'),t.endedEvent$),a(Lo(this.player,'playbackProgress').pipe(u((()=>po(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Lo(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Io.PLAYING),U(e.playbackState,P.PLAYING)})),a(Lo(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Io.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Lo(this.player,'playbackPaused'),(()=>{this.videoState.setState(Io.PAUSED),U(e.playbackState,P.PAUSED)})),a(Lo(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Io.READY&&this.videoState.setState(Io.READY)})),a(this.isLive$,t.isLive$),a(_o(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)),this.syncPlayback);const{playbackDuration$:l,ping$:c,connectionType$:m,connectionReused$:g}=eo(this.player);a(m,this.params.output.httpConnectionType$),a(g,this.params.output.httpConnectionReused$),a(l,this.maxSeekBackTime$),a(c.pipe(b()),t.firstBytesEvent$),a(Lo(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(y({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}}})})),a(d.pipe(f((t=>t>this.params.tuning.insufficientBufferRuleMargin)),b()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Lo(this.player,'manifestLoaded').pipe(b()).subscribe((()=>{this.subscription.add(Lo(this.player,'playbackPlaying').pipe(b(),v(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(ao(this.video,e.isLooped,i));const{volumeState$:S,looped$:T}=mo(this.video);this.subscription.add(no(this.video,e.volume,S,i)),this.subscription.add(S.subscribe(t.volume$,i)),this.subscription.add(T.subscribe(t.loopedEvent$))}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(Io.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Io.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=M(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,O.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Io.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Io.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var xo=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}},No=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 Oo(){return g()}function Bo(t){return Oo()-t}function Mo(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function Uo(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,u,h,l=!1,p=0,m=!1,f='arraybuffer',v=7e3,g=2e3,S=()=>{if(l)return;c(u);const t=Bo(u);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!l){if(--p>=0)return S(),void(r&&r());l=!0,h&&h(),i&&i()}},y=()=>{u=Oo(),o=new a,o.open('get',t);let i,s=0,r=0;const p=()=>(c(u),Math.max(u,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=Oo();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(l)return;c(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(p(),t)}h&&h(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),m){const t=()=>{c(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=Oo(),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=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(h=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),l=!0,h&&h()}};return T}class Vo{constructor(t){this.intervals=[],this.currentRate=0,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 r=e-t.start,a=t.end-t.start;i+=r;const n=t.bytes*r/a;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(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 qo{constructor(t,e,i,s,r){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}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=Oo(),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=Uo(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Oo()-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=Oo()}_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=Oo();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 r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._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(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}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 Fo{constructor(t){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=t,this.chunkRateEstimator=new Vo(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Mo(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=Mo(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',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.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,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const a=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:'playing'})):a()}))};a()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new qo(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,u=null,h=null,l=!1;const p=()=>{const t=n&&(!l||l===this.rep);return t||e('Not running!'),t},m=(t,e,i)=>{u&&u.abort(),u=Uo(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},f=(t,e,i)=>{c(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=Oo()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=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,u=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),l=()=>{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,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=i.dur.length-1;for(;a>=0&&(r-=i.dur[a],!(r<=0));--a);t=Math.min(a,i.dur.length-1-s),t=Math.max(t,0)}return u(t,!0)},m=(t,e,i)=>{h&&h.abort(),h=Uo(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{h=null})).withJSONResponse().send()};return{seek:(e,o)=>{m(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let h=0;for(let t=0;t<i.dur.length;++t)h+=i.dur[t];h>0&&(c(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(h/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 u(i);return l()}})(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)),l();if(!(n>=s))return u(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),u&&u.abort(),h&&h.abort(),c(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,u,l,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Oo(),s=Math.min(1e4,e-i);w=i;const r=()=>{h||p()&&E.seek((()=>{p()&&(w=Oo(),k(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},k=()=>{let e;for(;e=E.nextChunk(l);)l=e,R(e);const i=E.nextChunk(u);if(i){if(u&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));_(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Oo(),u=i.currentTime;!this.paused&&i.buffered.length>1&&g===u&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,T=d);const h=this._getBufferSizeSec();if(h>30)s(`Buffered ${h} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),S(),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&&(r=this.sourceBuffer.buffered.start(0),a=u,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},P=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(u)]),A(d,(function(){d=null,k()})))},D=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),_=t=>{p()&&f(D(t),((e,i)=>{if(p()){if(i/=1e3,d=e,u=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()))},R=t=>{p()&&(c(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{a=!0,P()})))};n=!0,E.seek((t=>{p()&&(w=Oo(),t?(l=t,!r(e)||t.startTS>e?_(t):(u=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):m(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},l}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.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,c(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),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,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.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=Oo();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(n&&t>r&&Bo(a)<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=Oo();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Uo(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;No(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0: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 Ho;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ho||(Ho={}));const Go=[Ho.PAUSED,Ho.PLAYING,Ho.READY],Yo=[Ho.PAUSED,Ho.PLAYING,Ho.READY];class zo{constructor(e){this.subscription=new i,this.videoState=new z(Ho.STOPPED),this.representations$=new t([]),this.textTracksManager=new uo,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new lo,this._dashCb=t=>{var e,i,r,a;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}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,a=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),r=null!==(i=xo(t.name))&&void 0!==i?i:G(t.video),n=t.bitrate/1e3,o={...t.video};if(!r)continue;const d={id:s,quality:r,bitrate:n,size:o};a.push({track:d,representation:t})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===Ho.MANIFEST_READY&&this.videoState.setState(Ho.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(a=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===a?void 0:a.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)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r!==P.STOPPED){if(!i){if(Yo.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}if((null==a?void 0:a.to)!==P.PAUSED&&o.state===C.Requested&&Go.includes(e))this.seek(o.position-this.liveOffset.getTotalPausedTime());else switch(e){case Ho.STOPPED:return this.videoState.startTransitionTo(Ho.MANIFEST_READY),void this.dash.attachSource(M(this.params.source.url));case Ho.MANIFEST_READY:this.videoState.startTransitionTo(Ho.READY),this.prepare();break;case Ho.READY:return void(r===P.PAUSED?this.videoState.setState(Ho.PAUSED):r===P.PLAYING&&(this.videoState.startTransitionTo(Ho.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Ho.PAUSED)}))));case Ho.PLAYING:return void(r===P.PAUSED&&(this.videoState.startTransitionTo(Ho.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Ho.PAUSED:return void(r===P.PLAYING&&(this.videoState.startTransitionTo(Ho.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(Ho.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(e)}}}else e!==Ho.STOPPED&&(this.videoState.startTransitionTo(Ho.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Ho.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const r=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};o(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=ho(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(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const a=mo(this.video);this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Ho.READY&&this.videoState.setState(Ho.READY)}),r)).add(a.pause$.subscribe((()=>{this.videoState.setState(Ho.PAUSED)}),r)).add(a.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Ho.PLAYING)}),r)).add(a.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(l(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(f(s)),position:a.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),r)).add(ao(this.video,this.params.desiredState.isLooped,r)).add(no(this.video,this.params.desiredState.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(this.params.output.volume$,r)).add(a.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(a.playing$.subscribe(this.params.output.firstFrameEvent$)).add(a.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&V[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case Ho.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case Ho.MANIFEST_READY:case Ho.READY:break;case Ho.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case Ho.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),r)).add(o(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Fo({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(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),u=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&s(d)?d:null===(a=Po(o.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()}))||void 0===a?void 0:a.id,l=null===(n=o.find((({track:t})=>t.id===h)))||void 0===n?void 0:n.representation;c(l,'Representations missing'),this.dash.startPlay(l,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(h),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;c(i,`No such representation ${t}`),this.dash.switchByName(i.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(M(this.params.source.url,i))}}var Qo=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?L.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}},jo=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)};class Wo{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,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=()=>{var e,i,s,r,a,n,o,d;if(c(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=to(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'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 Jo{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,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),null==e||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,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let u=0,h=0,l=0;const c=t=>{s(Jo._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=io(p)),this._lastXhr=new Wo(p,t.failoverHosts,(t=>{this._lastXhr=void 0,c(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}),null==r||r()}),(t=>{if(t.length-o>n&&c(t),0===h)return void(h=Date.now());l=t.length-u;const e=Date.now()-h;l>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:l,duration:e,speed:8*l/(e/1e3)}),l=0,u=t.length,h=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.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(),null==t||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=Jo._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(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class Ko{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},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='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=io(i)),new Wo(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,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,u,h,l,c,p,m,f,v,g,S,b,y,T,E,w,$;const k=t.getElementsByTagName('SegmentBase')[0],A=k&&r(k,'indexRange').split('-'),P=k&&k.getElementsByTagName('Initialization')[0],D=P&&r(P,'range').split('-');if(!D||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(h=null===(u=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===u?void 0:u[0])||void 0===h?void 0:h.data),c=null!==(l=e.getAttribute('lang'))&&void 0!==l?l:void 0;a&&n.push({id:r,url:a,language:c})}return}const _=Number(null===(c=t.attributes.getNamedItem('bandwidth'))||void 0===c?void 0:c.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const L=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;I=L?fo(L):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:_,baseURL:R,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(D[0]),initTo:Number(D[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*_/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,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 r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const u=t.refs[t.refs.length-1];u.toTime-u.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,r;const a=()=>{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 a;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');a=e.to-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.to&&(r=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*a)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}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 Jo({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 r=this._findRef(e);if(r){if(i){this._isLastRef(r)&&e>=r.toTime&&(e=r.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),a=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:r.fromTime}this._appendVector[String(r.fromTime)]=t,this._stream.load(t,r.fromOffset,r.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=r.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 r=.1;if(s.toTime<i.to+r){const e=this._findRef(s.toTime);e&&e.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((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){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.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 Xo;!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'}(Xo||(Xo={}));const Zo=[Xo.PAUSED,Xo.PLAYING];class td{constructor(s){this.videoState=new z(Xo.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new uo,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&xo(a.name))&&void 0!==s?s:G(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!n)continue;const h={id:t,quality:n,bitrate:o,size:d,fps:u};r.push({track:h,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(Xo.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return c(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)switch((null==s?void 0:s.to)!==P.PAUSED&&r.state===C.Requested&&Zo.includes(t)&&this.seek(r.position,r.forcePrecise),t){case Xo.STOPPED:return this.videoState.startTransitionTo(Xo.MANIFEST_LOADED),void this.prepare();case Xo.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Xo.INITIAL_REPRESENTATION_SELECTED);case Xo.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Xo.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Xo.METADATA_LOADED:return this.videoState.startTransitionTo(Xo.READY),void this.dash.updateRefsForCurrentTime();case Xo.READY:return void(i===P.PAUSED?(this.videoState.setState(Xo.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(Xo.PLAYING),this.playIfAllowed()));case Xo.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(Xo.PAUSED),this.video.pause()):(null==s?void 0:s.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Xo.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(Xo.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==Xo.STOPPED&&(this.videoState.startTransitionTo(Xo.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(Xo.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=s,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(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=ho(s.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(Do(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new co(this.video),this.dash=new Ko({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})},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',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=mo(this.video),c=(t,e)=>this.subscription.add(t.subscribe(e,i));c(d.timeUpdate$,t.position$),c(d.durationChange$,t.duration$),c(d.ended$,t.endedEvent$),c(d.looped$,t.loopedEvent$),c(d.error$,t.error$),c(d.isBuffering$,t.isBuffering$),c(d.playing$,t.firstFrameEvent$),c(d.canplay$,t.canplay$),this.subscription.add(d.seeking$.subscribe((()=>{r(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===Xo.PLAYING||this.videoState.getState()===Xo.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(ao(this.video,e.isLooped,i)),this.subscription.add(no(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),c(_o(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Xo.READY&&this.videoState.setState(Xo.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(Xo.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(Xo.PLAYING),U(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(Xo.METADATA_LOADED)}),i)).add(d.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}`,message:e,thrown:i})))).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$,a(this.video,'progress')).pipe(u((()=>{var t,e,i;const r=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),h=this.elementSize$.getValue(),l=n();let c;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!l&&s(d))c=d;else{const i=jo(this.video.buffered,1e3*this.video.currentTime),s=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,n=Math.min(i/s,1);c=null===(e=Po(a.map((({track:t})=>t)),{container:h,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:n,playbackRate:this.video.playbackRate,current:null===(t=a.find((({representation:t})=>t===r)))||void 0===t?void 0:t.track}))||void 0===e?void 0:e.id}return s(c)?null===(i=a.find((({track:t})=>t.id===c)))||void 0===i?void 0:i.representation:void 0})),l()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(f((t=>t.to===Xo.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(f(s))}).pipe(b()).subscribe((()=>this.videoState.setState(Xo.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(f(s),l(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=jo(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Do(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Qo(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(b(),v(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(f(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(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 n(t)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){No(this.video).then((t=>{t||(this.videoState.setState(Xo.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var ed,id,sd,rd,ad;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ed||(ed={})),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'}(id||(id={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(sd||(sd={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(rd||(rd={})),function(t){t.MP4='mp4',t.WEBM='webm'}(ad||(ad={}));var nd=(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 od='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;var dd,ud,hd=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let ld=!1;try{ld=hd()&&parseInt(null!==(ud=null===(dd=navigator.userAgent.match(/Version\/(\d+)/))||void 0===dd?void 0:dd[1])&&void 0!==ud?ud:'',10)<16}catch(t){console.error(t)}class cd{constructor(t){this.bufferFull$=new e,this.error$=new e,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown: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 r={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(r),this.pull()}))}async abort(t){return new Promise((e=>{let i;i=ld&&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)}pull(){var t;if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===i&&this.bufferFull$.next(this.currentTask.data.byteLength),t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===i||this.error$.next({id:`BufferTaskQueue:${i}`,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:n(e)}}}var pd;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(pd||(pd={}));class md{constructor({throughputEstimator:e,requestQuic:s}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new it,this.subscription=new i,this.fetchManifest=T(this.abortAllController.signal,async function*(t){let e=t;this.requestQuic&&(e=io(e));const i=yield et(e,{signal:this.abortAllController.signal}).catch(fd);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this)),this.fetch=T(this.abortAllController.signal,async function*(t,{rangeMethod:e=pd.HEADER,range:i,onProgress:s,priority:r='auto',signal:d,measureThroughput:u=!0}={}){var h,l,c,p;let m=t;const f=new Headers;if(i)switch(e){case pd.HEADER:f.append('Range',`${i.from}-${i.to}`);break;case pd.PARAM:{const t=new URL(m,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),m=t.toString();break}default:n(e)}this.requestQuic&&(m=io(m));let v=this.abortAllController.signal;if(d){const t=new it;if(this.subscription.add(o(a(this.abortAllController.signal,'abort'),a(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){fd(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){fd(t)}v=t.signal}const S=g(),b=yield et(m,{priority:r,headers:f,signal:v}).catch(fd),y=g();if(null===(h=this.throughputEstimator)||void 0===h||h.addRawRtt(y-S),!b)return null;if(!b.ok||!b.body)return Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const E=parseInt(null!==(l=b.headers.get('Content-Length'))&&void 0!==l?l:'',10)||i&&i.to-i.from+1||NaN;if(!E){const t=yield b.arrayBuffer();return null===(c=this.throughputEstimator)||void 0===c||c.addRawSpeed(t.byteLength,g()-y),null==s||s(new DataView(t),t.byteLength),t}if(!s&&!u)return b.arrayBuffer();const[w,$]=b.body.tee(),k=w.getReader();u&&(null===(p=this.throughputEstimator)||void 0===p||p.trackStream($));let A=0;const P=new ArrayBuffer(E),D=new Uint8Array(P),_=new DataView(P);let R=!1;const I=t=>{R=!0,fd(t)},L=T(v,async function*({done:t,value:e}){0===A&&this.lastRequestFirstBytes$.next(g()-S),v.aborted||(t?null==s||s(_,A):e&&(D.set(e,A),A+=e.byteLength,null==s||s(_,A),yield null==k?void 0:k.read().then(L,I)))}.bind(this));return yield null==k?void 0:k.read().then(L,I),R?null:P}.bind(this)),this.fetchByteRangeRepresentation=T(this.abortAllController.signal,async function*(t,e,i){if(t.type!==sd.BYTE_RANGE)return null;const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,u=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,u=r+1===a,u&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0);const h=yield this.fetch(t.url,{rangeMethod:pd.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1});if(!h)return null;const l=new DataView(h,s-o,r-o+1);if(!e.validateData(l))throw new Error('Invalid media file');const c=e.parseInit(l);let p;if(u&&void 0!==a&&void 0!==n)p=new DataView(h,a-o,n-a+1);else{const s=e.getIndexRange(c);if(s){const e=yield this.fetch(t.url,{rangeMethod:pd.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,c);return{dataView:new DataView(h),segments:m}}.bind(this)),this.fetchTemplateRepresentation=T(this.abortAllController.signal,async function*(t,e){if(t.type!==sd.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:rd.NONE,size:void 0}))),dataView:new DataView(s)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=s}onHeadersReceived(t){const{type:e,reused:i}=Qo(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}async fetchRepresentation(t,e,i='auto'){var s,r;const{type:a}=t;switch(a){case sd.BYTE_RANGE:return null!==(s=await this.fetchByteRangeRepresentation(t,e,i))&&void 0!==s?s:null;case sd.TEMPLATE:return null!==(r=await this.fetchTemplateRepresentation(t,i))&&void 0!==r?r:null;default:n(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const fd=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},vd=new TextDecoder('ascii'),gd=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=vd.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}},Sd={validateData:t=>'ftyp'===vd.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=gd(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=4294967295&r();let u=n/a*1e3,h=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:rd.NONE,time:{from:u,to:u+o},byte:{from:h,to:h+s-1}}),u+=o,h+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const r=new DataView(t.buffer,t.byteOffset+e);try{const i=gd(r);if(s||(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 bd,yd;!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'}(bd||(bd={})),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'}(yd||(yd={}));const Td={[bd.EBML]:{type:yd.Master},[bd.EBMLVersion]:{type:yd.UnsignedInteger},[bd.EBMLReadVersion]:{type:yd.UnsignedInteger},[bd.EBMLMaxIDLength]:{type:yd.UnsignedInteger},[bd.EBMLMaxSizeLength]:{type:yd.UnsignedInteger},[bd.DocType]:{type:yd.String},[bd.DocTypeVersion]:{type:yd.UnsignedInteger},[bd.DocTypeReadVersion]:{type:yd.UnsignedInteger},[bd.Void]:{type:yd.Binary},[bd.Segment]:{type:yd.Master},[bd.SeekHead]:{type:yd.Master},[bd.Seek]:{type:yd.Master},[bd.SeekID]:{type:yd.Binary},[bd.SeekPosition]:{type:yd.UnsignedInteger},[bd.Info]:{type:yd.Master},[bd.TimestampScale]:{type:yd.UnsignedInteger},[bd.Duration]:{type:yd.Float},[bd.Tracks]:{type:yd.Master},[bd.Chapters]:{type:yd.Master},[bd.Cluster]:{type:yd.Master},[bd.Timestamp]:{type:yd.UnsignedInteger},[bd.SilentTracks]:{type:yd.Master},[bd.SilentTrackNumber]:{type:yd.UnsignedInteger},[bd.Position]:{type:yd.UnsignedInteger},[bd.PrevSize]:{type:yd.UnsignedInteger},[bd.SimpleBlock]:{type:yd.Binary},[bd.BlockGroup]:{type:yd.Master},[bd.EncryptedBlock]:{type:yd.Binary},[bd.Attachments]:{type:yd.Master},[bd.Tags]:{type:yd.Master},[bd.Cues]:{type:yd.Master},[bd.CuePoint]:{type:yd.Master},[bd.CueTime]:{type:yd.UnsignedInteger},[bd.CueTrackPositions]:{type:yd.Master},[bd.CueTrack]:{type:yd.UnsignedInteger},[bd.CueClusterPosition]:{type:yd.UnsignedInteger},[bd.CueRelativePosition]:{type:yd.UnsignedInteger},[bd.CueDuration]:{type:yd.UnsignedInteger},[bd.CueBlockNumber]:{type:yd.UnsignedInteger},[bd.CueCodecState]:{type:yd.UnsignedInteger},[bd.CueReference]:{type:yd.Master},[bd.CueRefTime]:{type:yd.UnsignedInteger}},Ed=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=wd(t,i),r=s in Td,a=r?Td[s].type:yd.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),u=((n&255>>o)<<8*(o-1))+wd(d),h=i+o;let l;return l=h+u>t.byteLength?new DataView(t.buffer,t.byteOffset+h):new DataView(t.buffer,t.byteOffset+h,u),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+u,value:l,valueSize:u}},wd=(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},$d=(t,e)=>{switch(e){case yd.SignedInteger:return t.getInt8(0);case yd.UnsignedInteger:return wd(t);case yd.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case yd.String:return new TextDecoder('ascii').decode(t);case yd.UTF8:return new TextDecoder('utf-8').decode(t);case yd.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case yd.Master:case yd.Binary:return t;default:n(e)}},kd=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Ed(s);if(!e(r))return;r.type===yd.Master&&kd(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Ad=[bd.Info,bd.SeekHead,bd.Tracks,bd.Chapters,bd.Cluster,bd.Cues,bd.Attachments,bd.Tags],Pd=[bd.Timestamp,bd.SilentTracks,bd.SilentTrackNumber,bd.Position,bd.PrevSize,bd.SimpleBlock,bd.BlockGroup,bd.EncryptedBlock],Dd={validateData:t=>{if(t.getUint32(0)!==bd.EBML)return!1;let e,i,s;const r=Ed(t);return kd(r.value,(({tag:t,type:r,value:a})=>(t===bd.EBMLReadVersion?e=$d(a,r):t===bd.DocType?i=$d(a,r):t===bd.DocTypeReadVersion&&(s=$d(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,u=!1;return kd(t,(({tag:t,type:h,value:l,valueSize:c})=>{if(t===bd.SeekID){const t=$d(l,h);n=wd(t)}else t!==bd.SeekPosition&&(n=void 0);return t===bd.Segment?(e=l.byteOffset,i=l.byteOffset+c):t===bd.Info?o=!0:t===bd.SeekHead?d=!0:t===bd.TimestampScale?s=$d(l,h):t===bd.Duration?r=$d(l,h):t===bd.SeekPosition&&n===bd.Cues?a=$d(l,h):o&&d&&Ad.includes(t)&&(u=!0),!u})),c(e,'Failed to parse webm Segment start'),c(i,'Failed to parse webm Segment end'),c(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},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,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return kd(t,(({tag:t,type:e,value:s})=>{switch(t){case bd.Cues:i=!0;break;case bd.CuePoint:o&&a(o)&&n.push(o),o={};break;case bd.CueTime:o&&(o.time=$d(s,e));break;case bd.CueTrackPositions:break;case bd.CueClusterPosition:o&&(o.position=$d(s,e));break;default:i&&Ad.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:rd.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{kd(t,(s=>s.tag===bd.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!Pd.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[bd.SimpleBlock,bd.BlockGroup,bd.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class _d{constructor(o,d,u,h,{fetcher:l,tuning:p,getCurrentPosition:m}){switch(this.onLastSegment$=new t(!1),this.fullyBuffered$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.gaps=[],this.subscription=new i,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new it,this.destroyAbortController=new it,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=T(this.destroyAbortController.signal,async function*(t){const e=this.representations.get(t);c(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new cd(this.sourceBuffer),this.subscription.add(a(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(a(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>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(c(i,'No init buffer for starting representation'),c(r,'No segments for starting representation'),!(i instanceof ArrayBuffer))return;let n=0;for(const t of r)t.time.from-n>=300&&this.gaps.push({representation:e.id,from:n,to:t.time.from}),n=t.time.to;s(e.duration)&&e.duration-n>=300&&this.gaps.push({representation:e.id,from:n,to:e.duration}),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=T(this.destroyAbortController.signal,async function*(t){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;this.switchingToRepresentationId=t;const e=this.representations.get(t);c(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)),this.fetcher=l,this.tuning=p,this.forwardBufferTarget=p.dash.forwardBufferTargetAuto,this.getCurrentPosition=m,this.container=u,u){case ad.MP4:this.containerParser=Sd;break;case ad.WEBM:this.containerParser=Dd;break;default:n(u)}this.initData=new Map(h.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(h.map((t=>[t.id,t]))),this.kind=o,this.mediaSource=d,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new it,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(c(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=jo(this.sourceBuffer.buffered,t),r=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(a=r)}let n=[];if(isFinite(this.bufferLimit)&&(t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e})(this.sourceBuffer.buffered)>=.8*this.bufferLimit)this.pruneBuffer(1/0);else 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=bo(n,0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===rd.FED&&!n.length&&jo(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=bo(i,-1);o&&o.status===rd.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){var e,i,s;const r=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!r)return;const a=this.segments.get(r);if(!a)return;const n=a.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.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===rd.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==sd.BYTE_RANGE)return t.slice(s,s+1);const r=t;let a=0;const n=[];for(let t=s;t<r.length&&a<=this.tuning.dash.segmentRequestSize;t++){const e=r[t];if(a+=e.byte.to+1-e.byte.from,e.status!==rd.NONE)break;n.push(e)}return n}async loadSegments(t,e,i='auto'){if(!t.length)return;let s,r,a=t;const{type:o}=e.segmentReference;switch(o){case sd.BYTE_RANGE:s=e.segmentReference.url,r={from:bo(t,0).byte.from,to:bo(t,-1).byte.to};break;case sd.TEMPLATE:{const i=bo(t,0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),a=[i];break}default:n(o)}for(const t of a)t.status=rd.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,fedBytes:0,representationId:e.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await T(d,async function*(){const t=E(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise((e=>setTimeout(e,t)))}.bind(this))(),d.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:pd.PARAM,range:r,onProgress:(t,i)=>{if(!d.aborted)try{this.onSomeDataLoaded(t,e.id,r?r.from:0,i,d)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:d,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){var e;let i=!1;const r=this.getCurrentPosition();if(this.sourceBuffer&&s(r)){i=jo(null===(e=this.sourceBuffer)||void 0===e?void 0:e.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,i||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,r){if(!this.activeSegments.size)return;const a=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=rd.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===rd.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=rd.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,u=t.byteLength;for(const o of this.activeSegments){const{segment:h}=o,l=d===sd.BYTE_RANGE,c=l?h.byte.to-h.byte.from+1:u;if(o.representationId!==e)continue;if(!(!l||h.byte.from>=i&&h.byte.to<i+t.byteLength))continue;if(r.aborted){a(o);continue}const p=l?h.byte.from-i:0,m=p<s,f=(l?h.byte.to-i:t.byteLength)<=s;if(h.status===rd.DOWNLOADING&&m&&f){h.status=rd.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,c);this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?n(o):a(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&m&&(o.loadedBytes=Math.min(c,s-p),o.loadedBytes>o.fedBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.fedBytes,o.loadedBytes-o.fedBytes),i=o.loadedBytes===c?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(h.status=rd.PARTIALLY_FED,o.fedBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,r).then((t=>{!t||r.aborted?a(o):o.fedBytes===c&&n(o)})))}}}abortSegment(t){t.status===rd.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=rd.NONE)),t.status=rd.NONE):t.status=rd.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 r=s instanceof Promise;e||(e=r),null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=od((()=>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?T(this.destroyAbortController.signal,async function*(){const t=E(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,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,r),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',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=>{var e;a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;s+=i};for(const r of i){if(r.time.to>=e||s>=t)break;r.status===rd.FED&&d(r)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const r of i){if(r.time.from<e+this.forwardBufferTarget||s>t)break;r.status===rd.FED&&d(r)}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a/1e3,n/1e3)}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),r=1e3*this.sourceBuffer.buffered.end(t);if(!(r<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&r>=i.time.to){e=void 0;break}r>i.time.from&&r<i.time.to&&(e.from=r),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=od((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',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=1e3*this.sourceBuffer.buffered.start(e),s=1e3*this.sourceBuffer.buffered.end(e);t.push({from:i,to:s})}const e=this.tuning.dash.segmentTimelineTolerance;for(const i of this.segments.values())for(const s of i){const i=t.some((t=>t.from-e<=s.time.from&&t.to+e>=s.time.to));s.status!==rd.FED||i||(s.status=rd.NONE)}}}const Rd=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='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},Id=(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},Ld=['timeupdate','progress','play','seeked','stalled'];var Cd,xd;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Cd||(Cd={}));class Nd{constructor(r){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new z(Cd.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.gapWatchdogStarted=!1,this.destroyController=new it,this.initManifest=T(this.destroyController.signal,async function*(t,e){this.element=t,this.state$.startTransitionTo(Cd.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t})));if(!i)return null;let r;try{r=((t,e)=>{var i,r,a,n,o,d,u,h,l,c,p,m,f,v,g,S,b,y,T,E,w,$,k,A,P,D,_,R,I,L,C,x,N,O,B;const M={video:[],audio:[],text:[]},U=(new DOMParser).parseFromString(t,'application/xml').children[0],V=U.getElementsByTagName('Period')[0],q=V.children;let F;const H=U.getAttribute('mediaPresentationDuration'),G=V.getAttribute('duration');if(H)F=Rd(H);else if(G){const t=Rd(G);s(t)&&(F=t)}let Y=0;const z=null!==(r=null===(i=U.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==r?r:[],Q=z.includes(id.WEBM_AS_IN_FFMPEG)||z.includes(id.WEBM_AS_IN_SPEC)?ad.WEBM:ad.MP4;for(const t of q){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==i?void 0:i.split('/')[0],U=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],V=t.querySelectorAll('Representation');if('text'!==r)for(const a of V){const n=null!==(d=a.getAttribute('mimeType'))&&void 0!==d?d:i,o=null!==(h=null!==(u=a.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==h?h:'',V=null!==(c=null!==(l=a.getAttribute('contentType'))&&void 0!==l?l:null==n?void 0:n.split('/')[0])&&void 0!==c?c:r,q=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],H=parseInt(null!==(f=a.getAttribute('width'))&&void 0!==f?f:'',10),G=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),Q=parseInt(null!==(g=a.getAttribute('bandwidth'))&&void 0!==g?g:'',10)/1e3,j=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',W=null!==(b=a.getAttribute('quality'))&&void 0!==b?b:void 0,J=j?fo(j):void 0,K=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(Y++).toString(10)}@${'video'===V?`${G}p`:'audio'===V?`${Q}Kbps`:o}`,X=null!==(w=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==w?w:'',Z=new URL(X,e).toString(),tt=[...z,...U,...q];let et;const it=a.querySelector('SegmentBase'),st=a.querySelector('SegmentTemplate');if(it){const t=null!==(k=null===($=a.querySelector('SegmentBase Initialization'))||void 0===$?void 0:$.getAttribute('range'))&&void 0!==k?k:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},r=null===(A=a.querySelector('SegmentBase'))||void 0===A?void 0:A.getAttribute('indexRange'),[n,o]=r?r.split('-').map((t=>parseInt(t,10))):[],d=r?{from:n,to:o}:void 0;et={type:sd.BYTE_RANGE,url:Z,initRange:s,indexRange:d}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(P=a.getAttribute('id'))&&void 0!==P?P:void 0,bandwidth:null!==(D=a.getAttribute('bandwidth'))&&void 0!==D?D:void 0},e=parseInt(null!==(_=st.getAttribute('timescale'))&&void 0!==_?_:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),r=null!==(L=parseInt(null!==(I=st.getAttribute('startNumber'))&&void 0!==I?I:'',10))&&void 0!==L?L:1,n=Id(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(C=st.querySelectorAll('SegmentTimeline S'))&&void 0!==C?C:[],d=[];let u=r,h=0;for(const i of o){const r=1e3*parseInt(null!==(x=i.getAttribute('d'))&&void 0!==x?x:'',10),a=parseInt(null!==(N=i.getAttribute('r'))&&void 0!==N?N:'',10)||0,n=null!==(B=parseInt(null!==(O=i.getAttribute('t'))&&void 0!==O?O:'',10))&&void 0!==B?B:void 0;for(let i=0;i<a+1;i++){const i=Id(s,{...t,segmentNumber:u.toString(10),segmentTime:n.toString(10)}),a=n?n/e:h;h+=r/e;const o=h;u++,d.push({time:{from:a,to:o},url:i})}}et={type:sd.TEMPLATE,baseUrl:Z,initUrl:n,segments:d}}}if(!V||!n)continue;const rt={video:ed.VIDEO,audio:ed.AUDIO,text:ed.TEXT}[V];rt&&M[rt].push({id:K,kind:rt,segmentReference:et,profiles:tt,duration:F,bitrate:Q,mime:n,codecs:o,width:H,height:G,fps:J,quality:W})}}return{duration:F,container:Q,representations:M}})(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!r)return null;const a=({mime:e,codecs:i})=>{var s,r,a;return Boolean((null===(s=t.canPlayType)||void 0===s?void 0:s.call(t,e))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${e}; codecs="${i}"`)))};return this.manifest={...r,representations:to(Object.entries(r.representations).map((([t,e])=>[t,e.filter(a)])))},this.manifest.representations.video.length?this.state$.setState(Cd.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}.bind(this)),this.initRepresentations=T(this.destroyController.signal,async function*(t,e){c(this.manifest),c(this.element),this.state$.startTransitionTo(Cd.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 _d(ed.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new _d(ed.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=o(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),n=o(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(o(this.forceEnded$,y({allBuffersFull:r,someBufferEnded:n}).pipe(f((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var t;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(...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=>{var e;return null===(e=this.source)||void 0===e?void 0:e.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(Cd.REPRESENTATION_SELECTED),c(this.element),this.subscription.add(o(...Ld.map((t=>a(this.element,t))),a(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(a(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(a(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&nd(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}.bind(this)),this.tick=()=>{var t,e;if(!this.element||!this.videoBufferManager)return;const i=1e3*this.element.currentTime;this.videoBufferManager.maintain(i),null===(t=this.audioBufferManager)||void 0===t||t.maintain(i),!this.videoBufferManager.gaps.length&&!(null===(e=this.audioBufferManager)||void 0===e?void 0:e.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=w(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=r.throughputEstimator,this.tuning=r.tuning,this.fetcher=new md({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}async switchRepresentation(t,e){const i={[ed.VIDEO]:this.videoBufferManager,[ed.AUDIO]:this.audioBufferManager,[ed.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}seek(t,e){var i,s,r,a,n;let o;c(this.element),c(this.videoBufferManager),o=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(null!==(i=this.videoBufferManager.findSegmentStartTime(t))&&void 0!==i?i:t,null!==(r=null===(s=this.audioBufferManager)||void 0===s?void 0:s.findSegmentStartTime(t))&&void 0!==r?r:t),nd(this.element.buffered,o)||(this.videoBufferManager.abort(),null===(a=this.audioBufferManager)||void 0===a||a.abort()),this.videoBufferManager.maintain(o),null===(n=this.audioBufferManager)||void 0===n||n.maintain(o),this.element.currentTime=o/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Cd.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}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of this.bufferManagers)for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xd||(xd={}));const Od=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?xo(a):void 0)&&void 0!==n?n:G({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},Bd=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=bo(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:bo(t,-1)};class Md{constructor(e){this.subscription=new i,this.videoState=new z(xd.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new uo,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ao,this.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&&(null==i?void 0:i.to)!==P.PAUSED&&t!==xd.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===xd.STOPPED)return this.videoState.startTransitionTo(xd.READY),void this.prepare();switch(t){case xd.READY:return void(e===P.PAUSED?(this.videoState.setState(xd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(xd.PLAYING),this.playIfAllowed()));case xd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(xd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case xd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(xd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==xd.STOPPED&&(this.videoState.startTransitionTo(xd.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(xd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=e,this.video=ho(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Do(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Nd({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=mo(this.video),r=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,r));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.playing$,t.firstFrameEvent$),n(i.canplay$,t.canplay$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(f(s),b(),v(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(ao(this.video,e.isLooped,r)),this.subscription.add(no(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),n(_o(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(xd.PLAYING),U(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(xd.PAUSED),U(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===xd.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(f((({to:t})=>t===Cd.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(xd.READY)})));const d=e=>t.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:e});this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a(this.video,'progress')).subscribe((()=>{var i,s,r,a,n,o,u,h;const l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l===Cd.NONE||!this.videoTracks.length)return;const m=l===Cd.MANIFEST_LOADED&&!p,f=l===Cd.REPRESENTATION_SELECTED&&!p,v=e.autoVideoTrackSwitching.getState(),g=e.videoTrack.getState(),S=null===(i=this.videoTracks.find((({track:{id:t}})=>t===g)))||void 0===i?void 0:i.track,b=t.currentVideoTrack$.getValue(),y=jo(this.video.buffered,1e3*this.video.currentTime),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),w=Math.max(S&&!v&&null!==(r=null===(s=this.audioRepresentations.get(S.id))||void 0===s?void 0:s.bitrate)&&void 0!==r?r:0,b&&null!==(n=null===(a=this.audioRepresentations.get(b.id))||void 0===a?void 0:a.bitrate)&&void 0!==n?n:0),$=Po(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:w,forwardBufferHealth:E,current:b,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),k=v?null!=$?$:S:null!=S?S:$;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),m){const t=k&&(null===(o=this.videoTracks.find((({track:t})=>t===k)))||void 0===o?void 0:o.representation);c(t),this.player.initRepresentations(t.id,null===(u=this.audioRepresentations.get(t.id))||void 0===u?void 0:u.id)}else if(f){const t=k&&(null===(h=this.videoTracks.find((({track:t})=>t===k)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(ed.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(ed.AUDIO,e.id).catch(d)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(l(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const m=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(m.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=Od(t);if(s){this.videoTracks.push({track:s,representation:t});const r=Bd(e,i,t);r&&this.audioRepresentations.set(t.id,r)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){No(this.video).then((t=>{t||(this.videoState.setState(xd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Ud={};var Vd;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Vd||(Vd={}));const qd=(t,e)=>new S((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class Fd{constructor(t){this.subscription=new i,this.videoState=new z(Vd.INITIALIZING),this.textTracksManager=new uo,this.trackLevels=new Map,this.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!==Vd.INITIALIZING)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Vd.STOPPED:break;case Vd.READY:case Vd.PLAYING:case Vd.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Vd.PLAYING:break;case Vd.STOPPED:this.prepare();break;case Vd.READY:case Vd.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case Vd.PAUSED:break;case Vd.STOPPED:this.prepare();break;case Vd.READY:this.videoState.setState(Vd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED);break;case Vd.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}},this.video=ho(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Do(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.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',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);import('hls.js').then((e=>{t||(Ud.Hls=e.default,Ud.Events=e.default.Events,this.init())}),e).finally((()=>{window.clearTimeout(i),t=!0}))}init(){c(Ud.Hls,'hls.js not loaded'),this.hls=new Ud.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Vd.STOPPED)}subscribe(){c(Ud.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=mo(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadStart$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),this.subscription.add(ao(this.video,t.isLooped,i)),this.subscription.add(no(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qd(this.hls,Ud.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Vd.PLAYING),U(t.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Vd.PAUSED),U(t.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Vd.READY&&this.videoState.setState(Vd.READY),this.videoState.getState()===Vd.PLAYING&&this.playIfAllowed()}),i)),n(qd(this.hls,Ud.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=xo(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:G({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:u,level:e}),t.push(u),t}),[])))),e.availableVideoTracks$),n(qd(this.hls,Ud.Events.LEVEL_LOADING).pipe(u((({url:t})=>Do(t)))),e.hostname$),this.subscription.add(ro(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 d=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},l=qd(this.hls,Ud.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>d(this.hls.levels[t]))));l.pipe(f(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ro(t.videoTrack,(()=>{var t;return null===(t=d(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),a=this.hls.currentLevel,n=this.hls.levels[a];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:l.pipe(u((t=>null==t?void 0:t.id))),onError:i})),n(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const m=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(m.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Vd.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Vd.PLAYING);await No(this.video)||(this.videoState.setState(Vd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Vd.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(Vd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)}}const Hd=t=>{let e=null;if(t.QUALITY&&(e=xo(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=G({width:i,height:s})}return null!=e?e:null},Gd=async(t,e=t)=>{var i;const s=await et(t),r=(await s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=to(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=Hd(n);let u;n.BANDWIDTH&&(u=parseInt(n.BANDWIDTH,10)/1e3||void 0),!u&&n['AVERAGE-BANDWIDTH']&&(u=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let l;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(l={width:t,height:e})}const c=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:c,bandwidth:u,size:l,fps:h})}return a};var Yd,zd,Qd,jd,Wd,Jd,Kd,Xd,Zd,tu,eu,iu,su,ru,au,nu,ou,du,uu,hu;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Yd||(Yd={}));class lu{constructor(e){var s;this.subscription=new i,this.videoState=new z(Yd.STOPPED),this.textTracksManager=new uo,this.manifests$=new t([]),this.liveOffset=new lo,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Yd.STOPPED&&(this.videoState.startTransitionTo(Yd.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(Yd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Yd.STOPPED)return this.videoState.startTransitionTo(Yd.READY),void this.prepare();if(s||r){const t=this.videoState.getState();return this.videoState.setState(Yd.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested)return this.videoState.startTransitionTo(Yd.READY),this.seek(a.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Yd.READY:return void(e===P.PAUSED?(this.videoState.setState(Yd.PAUSED),this.liveOffset.pause(),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Yd.PLAYING),this.playIfAllowed()));case Yd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Yd.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Yd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Yd.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())):(null==i?void 0:i.to)===P.PAUSED&&(U(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Yd.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=ho(e.container),this.params.output.element$.next(this.video);const r={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),Gd(M(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([r,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(Do(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(s=e.source.maxSeekBackTime)&&void 0!==s?s:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},r=mo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.ended$,t.endedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(no(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Yd.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Yd.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Yd.READY&&this.videoState.setState(Yd.READY),this.videoState.getState()===Yd.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(),r=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(Do(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Yd.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(f(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:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,h(['init'])).pipe(p(0));this.subscription.add(n.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=M(t.url,this.liveOffset.getTotalOffset());this.video.setAttribute('src',e),this.video.load(),(async t=>{const e=await et(t,{method:'HEAD'});return e.headers.has('X-Playback-Duration')?parseInt(e.headers.get('X-Playback-Duration'),10):void 0})(e).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){No(this.video).then((t=>{t||(this.videoState.setState(Yd.PAUSED),this.liveOffset.pause(),U(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()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(zd||(zd={}));class cu{constructor(e){this.subscription=new i,this.videoState=new z(zd.STOPPED),this.textTracksManager=new uo,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==zd.STOPPED&&(this.videoState.startTransitionTo(zd.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(zd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===zd.STOPPED)return this.videoState.startTransitionTo(zd.READY),void this.prepare();if(s||r){const t=this.videoState.getState();this.videoState.setState(zd.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case zd.READY:return void(e===P.PAUSED?(this.videoState.setState(zd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(zd.PLAYING),this.playIfAllowed()));case zd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(zd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case zd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(zd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));case zd.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=ho(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:B.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Do(this.params.source.url)),Gd(this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},r=mo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(ao(this.video,e.isLooped,i)),this.subscription.add(no(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(zd.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(zd.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===zd.READY&&this.videoState.setState(zd.READY),this.videoState.getState()===zd.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(),r=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(Do(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===zd.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:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.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(){No(this.video).then((t=>{t||(this.videoState.setState(zd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Qd||(Qd={}));class pu{constructor(t){this.subscription=new i,this.videoState=new z(Qd.STOPPED),this.trackUrls={},this.textTracksManager=new uo,this.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!==Qd.STOPPED&&(this.videoState.startTransitionTo(Qd.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(Qd.STOPPED),U(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(t===Qd.STOPPED)return this.videoState.startTransitionTo(Qd.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case Qd.READY:return void(e===P.PAUSED?(this.videoState.setState(Qd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Qd.PLAYING),this.playIfAllowed()));case Qd.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Qd.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&U(this.params.desiredState.playbackState,P.PLAYING));case Qd.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Qd.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&U(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}},this.params=t,this.video=ho(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.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},r=mo(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(ao(this.video,e.isLooped,i)),this.subscription.add(no(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Qd.PLAYING),U(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Qd.PAUSED),U(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Qd.READY&&this.videoState.setState(Qd.READY);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===Qd.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();c(i,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[i];c(s,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(s=io(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(Do(s))}playIfAllowed(){No(this.video).then((t=>{t||(this.videoState.setState(Qd.PAUSED),U(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class mu{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 fu=hd(),vu=(null===(jd=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===jd?void 0:jd.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),gu=document.createElement('video'),Su={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Jd=null===(Wd=window.SourceBuffer)||void 0===Wd?void 0:Wd.prototype)||void 0===Jd?void 0:Jd.appendBuffer)),hls:Boolean((null===(Kd=gu.canPlayType)||void 0===Kd?void 0:Kd.call(gu,'application/x-mpegurl'))||(null===(Xd=gu.canPlayType)||void 0===Xd?void 0:Xd.call(gu,'vnd.apple.mpegURL')))},bu={mp4:Boolean(null===(Zd=gu.canPlayType)||void 0===Zd?void 0:Zd.call(gu,'video/mp4')),webm:Boolean(null===(tu=gu.canPlayType)||void 0===tu?void 0:tu.call(gu,'video/webm'))},yu={h264:Boolean(null===(iu=null===(eu=window.MediaSource)||void 0===eu?void 0:eu.isTypeSupported)||void 0===iu?void 0:iu.call(eu,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(ru=null===(su=window.MediaSource)||void 0===su?void 0:su.isTypeSupported)||void 0===ru?void 0:ru.call(su,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(nu=null===(au=window.MediaSource)||void 0===au?void 0:au.isTypeSupported)||void 0===nu?void 0:nu.call(au,'video/webm; codecs="vp9"')),aac:Boolean(null===(du=null===(ou=window.MediaSource)||void 0===ou?void 0:ou.isTypeSupported)||void 0===du?void 0:du.call(ou,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(hu=null===(uu=window.MediaSource)||void 0===uu?void 0:uu.isTypeSupported)||void 0===hu?void 0:hu.call(uu,'audio/webm; codecs="opus"'))},Tu=(yu.h264||yu.h265)&&yu.aac,Eu=!fu,wu=vu||fu,$u=!Su.hls||!wu;const ku=3e4,Au=18e4,Pu=3,Du=100,_u={cacheDuration:12e4},Ru={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Iu={maxPausedTime:3e4},Lu={maxPausedTime:3e4};class Cu{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.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)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,o=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new mu(o.filter((t=>s(r.sources[t]))).filter((t=>{switch(t){case D.DASH:return Su.mse&&bu.mp4&&Tu&&Eu;case D.DASH_SEP:case D.DASH_SEP_VK:return Su.mse&&bu.mp4&&Tu;case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.DASH_LIVE_WEBM:return Su.mse&&bu.webm&&yu.vp9&&yu.opus;case D.DASH_LIVE:return Su.mse&&bu.mp4&&Tu;case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:return Su.mse&&bu.mp4&&Tu;case D.HLS:case D.HLS_LIVE:case D.HLS_ONDEMAND:return Su.hls&&bu.mp4&&wu;case D.HLS_JS:return Su.mse&&bu.mp4&&Tu&&$u;case D.MPEG:return bu.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new mu(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}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',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();const t=this.current$.getValue().destination;c(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 r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case _.SCREEN:return this.createScreenProvider(e);case _.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r={container:i,source:null,desiredState:s,output:this.providerOutput,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case D.DASH:{const i=e[t];return c(i),new td({...r,source:i,config:_u})}case D.DASH_ONDEMAND_VK:case D.DASH_SEP_VK:case D.DASH_WEBM_VK:{const i=e[t];return c(i),new Md({...r,source:i})}case D.DASH_SEP:case D.DASH_WEBM:case D.DASH_ONDEMAND:case D.DASH_LIVE_WEBM:{const i=e[t];return c(i),new Co({...r,source:i,format:t,config:Lu})}case D.HLS:case D.HLS_ONDEMAND:{const i=e[t];return c(i),new cu({...r,source:i})}case D.HLS_LIVE:{const i=e[t];return c(i),new lu({...r,source:i,config:Iu})}case D.HLS_JS:{const i=e[t];return c(i),new Fd({...r,source:i})}case D.MPEG:{const i=e[t];return c(i),new pu({...r,source:i})}case D.DASH_LIVE:{const i=e[t];return c(i),new zo({...r,source:i,config:Ru})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return c(n),new j({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_.CHROMECAST:_.SCREEN}chooseFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.next();case _.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case _.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case _.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let t=[],r=0;const a=new i;var n;return a.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:ku,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(f((({type:t})=>void 0!==t)))},new S((t=>{const s=new i,r=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),a=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,l='unknown';return s.add(r.subscribe((t=>{h&&window.clearTimeout(h),l=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(a.subscribe((()=>{window.clearTimeout(h),l='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(l)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),a.add(this.providerError$.pipe($(Du,{leading:!1,trailing:!0})).subscribe((()=>{const e=Date.now();this.current$.getValue().destination===_.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(t[r])&&e<t[r]+Au?(t=[],this.switchToNextProvider()):(t[r]=e,this.reinitProvider()),r=(r+1)%Pu}))),a}}const xu=(t,e,i)=>i*e+(1-i)*t;class Nu{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,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 s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new $o(`raw_${s}`),this.smoothedSeries$=new $o(`smoothed_${s}`),this.reportedSeries$=new $o(`reported_${s}`),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=xu(this.slow,t,this.params.emaAlphaSlow),this.fast=xu(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 Ou;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Ou||(Ou={}));const Bu=new Map;let Mu=Ou.RUNTIME;const Uu=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Uu,'test'),localStorage.removeItem(Uu),Mu=Ou.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Uu),Mu=Ou.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Mu=Ou.RUNTIME}}})();const Vu=(t,e)=>{switch(Mu){case Ou.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ou.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ou.RUNTIME:return void Bu.set(t,e);default:n(Mu)}},qu=window.navigator.connection,Fu=()=>{const t=null==qu?void 0:qu.downlink;if(s(t)&&10!==t)return 1e3*t},Hu=()=>{const t=null==qu?void 0:qu.rtt;if(s(t)&&3e3!==t)return t},Gu=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Yu{constructor(e){var r,n;this.subscription=new i,this.concurrentDownloads=new Set,this.tuningConfig=e;const o=Yu.load('one_video_throughput')||(e.useBrowserEstimation?Fu():void 0)||5e3,d=null!==(n=null!==(r=Yu.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?Hu():void 0)&&void 0!==n?n:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(Gu(o,d,e.rttPenaltyRequestSize)),this.throughput=new Nu({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Nu({initial:d,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=Fu();t&&this.throughput.next(t);const e=Hu();s(e)&&this.rtt.next(e)};qu&&'onchange'in qu&&this.subscription.add(a(qu,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Vu('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Vu('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(y({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>Gu(t,i,e.rttPenaltyRequestSize))),f((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=g();const r=new i;switch(this.subscription.add(r),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:r.add(a(t,'progress').pipe(b()).subscribe((t=>{e=t.loaded,s=g()})));break;case 1:case 0:r.add(a(t,'loadstart').subscribe((()=>{e=0,s=g()})))}r.add(a(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=g(),a=t-e,n=r-s;this.addRawSpeed(a,n,1)}this.concurrentDownloads.delete(t),r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=g();let r=0,a=g();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=async({done:d,value:u})=>{d?(this.addRawSpeed(i,g()-s,1),this.concurrentDownloads.delete(t)):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&g()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,g()-a,this.concurrentDownloads.size),r=0,a=g()),await(null==e?void 0:e.read().then(o,n)))};this.concurrentDownloads.add(t),null==e||e.read().then(o,n)}addRawSpeed(t,e,i=1){if(Yu.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){var e;const i=(t=>{var e,i;switch(Mu){case Ou.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case Ou.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case Ou.RUNTIME:return Bu.get(t);default:n(Mu)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const zu={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:[D.DASH_WEBM,D.DASH_SEP,D.DASH_SEP_VK],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};const Qu=(t=(t=>t))=>({playbackState:e,seekState:s,playbackAbort$:a,looped$:n,position$:d})=>new S((h=>{let l;const c=e.transitionEnded$.pipe(f((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=e.stateChangeEnded$.pipe(f((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=s.stateChangeEnded$.pipe(f((({to:t})=>{var i,s;return t.state===C.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===P.PLAYING}))),v=s.stateChangeEnded$.pipe(f((({from:t,to:i})=>{var s,r;return t.state===C.Applying&&i.state===C.None&&(null!==(r=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:e.getState())===P.PLAYING}))),g=o(c,v).pipe(u((()=>t(d.getValue())))),S=o(o(p,m,a).pipe(u((()=>t(d.getValue())))),n.pipe(u(t)));return(new i).add(g.subscribe((e=>{l=t(e)}))).add(S.subscribe((e=>{const i=t(e);if(r(l)||l===i)return;const s={from:l,to:i};l=void 0,h.next(s)})))})),ju=Qu((t=>t)),Wu=Qu((t=>Math.round(1e3*t)+Date.now())),Ju={[_.SCREEN]:{vod:[D.HLS,D.HLS_ONDEMAND,D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS_JS,D.MPEG],live:[D.HLS_LIVE,D.DASH_LIVE,D.DASH_LIVE_WEBM]},[_.CHROMECAST]:{vod:[D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS,D.HLS_ONDEMAND,D.MPEG],live:[D.HLS_LIVE]}};class Ku{constructor(s={}){if(this.subscription=new i,this.logger=new k,this.isPlaybackStarted=!1,this.desiredState={playbackState:new z(P.STOPPED),seekState:new z({state:C.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),externalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({})},this.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({}),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(R.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={inited$:new e,started$:new e,startAttempt$: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},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:Eo},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(zu)){const s=zu[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?{...s,...r}:null!=r?r:s}return e})(s),this.chromecastInitializer=new x({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Yu(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)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(t){var e,i;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return c(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new Cu({screenFormatsPriority:[...Ju[_.SCREEN].live,...Ju[_.SCREEN].vod],chromecastFormatsPriority:[...Ju[_.CHROMECAST].live,...Ju[_.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},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(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.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),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===R.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()===R.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){c(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}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>({type:'external',...t})))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.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(){c(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(o(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.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$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(f((t=>t.to===P.PLAYING)),f((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=g(),this.events.inited$.next(),t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(f((t=>t.to===P.PLAYING||t.to===P.PAUSED)),p(0),b()).subscribe((t=>{const e=t.to===P.PLAYING,i=this.info.muted$.getValue(),s=e?i?I.SuccessWithoutSound:I.SuccessWithSound:I.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(f((t=>t.to===P.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).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()}})))}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}`,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)=>Y(t)?1:Y(e)?-1:q(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(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0: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})=>o(t.stateChangeEnded$.pipe(u((({to:t})=>{var e;return t.state===C.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),f(s)),e.pipe(f((()=>t.getState().state===C.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(v(!0)),e.providerOutput.seekedEvent$.pipe(v(!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',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(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(b(),u((()=>g()-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 n=new t(!0);this.subscription.add(e.current$.subscribe((()=>n.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(f((({to:t})=>t===P.PLAYING)),b()).subscribe((()=>n.next(!1))));let d=0;const h=o(e.providerOutput.isBuffering$,r,n).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=r.getValue()||n.getValue();return t&&!i})),l());this.subscription.add(h.subscribe((t=>{t?d=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(d),this.info.isStalled$.next(!1))})));const p=new i;this.subscription.add(p);const m=o(a(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(f((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(l()).subscribe((t=>{switch(c(this.providerContainer),p.unsubscribe(),t){case!0:p.add(Wu({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:m,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break;case!1:p.add(ju({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:m,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=>null==t?void 0: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(f((t=>t.length>0)),b()).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=Po(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(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(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;c(this.providerContainer),c(e),To={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{yo=t})),this.providerContainer.current$.subscribe((({type:t})=>wo('provider',t))),e.duration$.subscribe((t=>wo('duration',t))),e.availableVideoTracks$.pipe(f((t=>!!t.length)),b()).subscribe((t=>wo('tracks',t))),this.events.fatalError$.subscribe(new $o('fatalError')),this.events.managedError$.subscribe(new $o('managedError')),e.position$.subscribe(new $o('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new $o('quality')),this.info.currentBuffer$.subscribe(new $o('buffer')),e.isBuffering$.subscribe(new $o('isBuffering'))].forEach((t=>this.subscription.add(t))),wo('codecs',Object.keys(yu).filter((t=>yu[t])))}}const Xu='@vkontakte/videoplayer-core@2.0.67';export{R as ChromecastState,L as HttpConnectionType,P as PlaybackState,Ku as Player,Xu as SDK_VERSION,I as StartStatus,D as VideoFormat,B as VideoQuality};
|